PackageManagerService.java revision b49245f96233b7f89fb5d4ba52576131ca6fb47a
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, false);
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, false);
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                        false /* boot complete */);
2261            }
2262
2263            // Now that we know all the packages we are keeping,
2264            // read and update their last usage times.
2265            mPackageUsage.readLP();
2266
2267            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2268                    SystemClock.uptimeMillis());
2269            Slog.i(TAG, "Time to scan packages: "
2270                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2271                    + " seconds");
2272
2273            // If the platform SDK has changed since the last time we booted,
2274            // we need to re-grant app permission to catch any new ones that
2275            // appear.  This is really a hack, and means that apps can in some
2276            // cases get permissions that the user didn't initially explicitly
2277            // allow...  it would be nice to have some better way to handle
2278            // this situation.
2279            int updateFlags = UPDATE_PERMISSIONS_ALL;
2280            if (ver.sdkVersion != mSdkVersion) {
2281                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2282                        + mSdkVersion + "; regranting permissions for internal storage");
2283                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2284            }
2285            updatePermissionsLPw(null, null, updateFlags);
2286            ver.sdkVersion = mSdkVersion;
2287
2288            // If this is the first boot or an update from pre-M, and it is a normal
2289            // boot, then we need to initialize the default preferred apps across
2290            // all defined users.
2291            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2292                for (UserInfo user : sUserManager.getUsers(true)) {
2293                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2294                    applyFactoryDefaultBrowserLPw(user.id);
2295                    primeDomainVerificationsLPw(user.id);
2296                }
2297            }
2298
2299            // If this is first boot after an OTA, and a normal boot, then
2300            // we need to clear code cache directories.
2301            if (mIsUpgrade && !onlyCore) {
2302                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2303                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2304                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2305                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2306                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2307                    }
2308                }
2309                ver.fingerprint = Build.FINGERPRINT;
2310            }
2311
2312            checkDefaultBrowser();
2313
2314            // clear only after permissions and other defaults have been updated
2315            mExistingSystemPackages.clear();
2316            mPromoteSystemApps = false;
2317
2318            // All the changes are done during package scanning.
2319            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2320
2321            // can downgrade to reader
2322            mSettings.writeLPr();
2323
2324            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2325                    SystemClock.uptimeMillis());
2326
2327            mRequiredVerifierPackage = getRequiredVerifierLPr();
2328            mRequiredInstallerPackage = getRequiredInstallerLPr();
2329
2330            mInstallerService = new PackageInstallerService(context, this);
2331
2332            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2333            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2334                    mIntentFilterVerifierComponent);
2335
2336        } // synchronized (mPackages)
2337        } // synchronized (mInstallLock)
2338
2339        // Now after opening every single application zip, make sure they
2340        // are all flushed.  Not really needed, but keeps things nice and
2341        // tidy.
2342        Runtime.getRuntime().gc();
2343
2344        // Expose private service for system components to use.
2345        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2346    }
2347
2348    @Override
2349    public boolean isFirstBoot() {
2350        return !mRestoredSettings;
2351    }
2352
2353    @Override
2354    public boolean isOnlyCoreApps() {
2355        return mOnlyCore;
2356    }
2357
2358    @Override
2359    public boolean isUpgrade() {
2360        return mIsUpgrade;
2361    }
2362
2363    private String getRequiredVerifierLPr() {
2364        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2365        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2366                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2367
2368        String requiredVerifier = null;
2369
2370        final int N = receivers.size();
2371        for (int i = 0; i < N; i++) {
2372            final ResolveInfo info = receivers.get(i);
2373
2374            if (info.activityInfo == null) {
2375                continue;
2376            }
2377
2378            final String packageName = info.activityInfo.packageName;
2379
2380            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2381                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2382                continue;
2383            }
2384
2385            if (requiredVerifier != null) {
2386                throw new RuntimeException("There can be only one required verifier");
2387            }
2388
2389            requiredVerifier = packageName;
2390        }
2391
2392        return requiredVerifier;
2393    }
2394
2395    private String getRequiredInstallerLPr() {
2396        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2397        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2398        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2399
2400        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2401                PACKAGE_MIME_TYPE, 0, 0);
2402
2403        String requiredInstaller = null;
2404
2405        final int N = installers.size();
2406        for (int i = 0; i < N; i++) {
2407            final ResolveInfo info = installers.get(i);
2408            final String packageName = info.activityInfo.packageName;
2409
2410            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2411                continue;
2412            }
2413
2414            if (requiredInstaller != null) {
2415                throw new RuntimeException("There must be one required installer");
2416            }
2417
2418            requiredInstaller = packageName;
2419        }
2420
2421        if (requiredInstaller == null) {
2422            throw new RuntimeException("There must be one required installer");
2423        }
2424
2425        return requiredInstaller;
2426    }
2427
2428    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2429        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2430        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2431                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2432
2433        ComponentName verifierComponentName = null;
2434
2435        int priority = -1000;
2436        final int N = receivers.size();
2437        for (int i = 0; i < N; i++) {
2438            final ResolveInfo info = receivers.get(i);
2439
2440            if (info.activityInfo == null) {
2441                continue;
2442            }
2443
2444            final String packageName = info.activityInfo.packageName;
2445
2446            final PackageSetting ps = mSettings.mPackages.get(packageName);
2447            if (ps == null) {
2448                continue;
2449            }
2450
2451            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2452                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2453                continue;
2454            }
2455
2456            // Select the IntentFilterVerifier with the highest priority
2457            if (priority < info.priority) {
2458                priority = info.priority;
2459                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2460                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2461                        + verifierComponentName + " with priority: " + info.priority);
2462            }
2463        }
2464
2465        return verifierComponentName;
2466    }
2467
2468    private void primeDomainVerificationsLPw(int userId) {
2469        if (DEBUG_DOMAIN_VERIFICATION) {
2470            Slog.d(TAG, "Priming domain verifications in user " + userId);
2471        }
2472
2473        SystemConfig systemConfig = SystemConfig.getInstance();
2474        ArraySet<String> packages = systemConfig.getLinkedApps();
2475        ArraySet<String> domains = new ArraySet<String>();
2476
2477        for (String packageName : packages) {
2478            PackageParser.Package pkg = mPackages.get(packageName);
2479            if (pkg != null) {
2480                if (!pkg.isSystemApp()) {
2481                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2482                    continue;
2483                }
2484
2485                domains.clear();
2486                for (PackageParser.Activity a : pkg.activities) {
2487                    for (ActivityIntentInfo filter : a.intents) {
2488                        if (hasValidDomains(filter)) {
2489                            domains.addAll(filter.getHostsList());
2490                        }
2491                    }
2492                }
2493
2494                if (domains.size() > 0) {
2495                    if (DEBUG_DOMAIN_VERIFICATION) {
2496                        Slog.v(TAG, "      + " + packageName);
2497                    }
2498                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2499                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2500                    // and then 'always' in the per-user state actually used for intent resolution.
2501                    final IntentFilterVerificationInfo ivi;
2502                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2503                            new ArrayList<String>(domains));
2504                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2505                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2506                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2507                } else {
2508                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2509                            + "' does not handle web links");
2510                }
2511            } else {
2512                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2513            }
2514        }
2515
2516        scheduleWritePackageRestrictionsLocked(userId);
2517        scheduleWriteSettingsLocked();
2518    }
2519
2520    private void applyFactoryDefaultBrowserLPw(int userId) {
2521        // The default browser app's package name is stored in a string resource,
2522        // with a product-specific overlay used for vendor customization.
2523        String browserPkg = mContext.getResources().getString(
2524                com.android.internal.R.string.default_browser);
2525        if (!TextUtils.isEmpty(browserPkg)) {
2526            // non-empty string => required to be a known package
2527            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2528            if (ps == null) {
2529                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2530                browserPkg = null;
2531            } else {
2532                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2533            }
2534        }
2535
2536        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2537        // default.  If there's more than one, just leave everything alone.
2538        if (browserPkg == null) {
2539            calculateDefaultBrowserLPw(userId);
2540        }
2541    }
2542
2543    private void calculateDefaultBrowserLPw(int userId) {
2544        List<String> allBrowsers = resolveAllBrowserApps(userId);
2545        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2546        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2547    }
2548
2549    private List<String> resolveAllBrowserApps(int userId) {
2550        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2551        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2552                PackageManager.MATCH_ALL, userId);
2553
2554        final int count = list.size();
2555        List<String> result = new ArrayList<String>(count);
2556        for (int i=0; i<count; i++) {
2557            ResolveInfo info = list.get(i);
2558            if (info.activityInfo == null
2559                    || !info.handleAllWebDataURI
2560                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2561                    || result.contains(info.activityInfo.packageName)) {
2562                continue;
2563            }
2564            result.add(info.activityInfo.packageName);
2565        }
2566
2567        return result;
2568    }
2569
2570    private boolean packageIsBrowser(String packageName, int userId) {
2571        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2572                PackageManager.MATCH_ALL, userId);
2573        final int N = list.size();
2574        for (int i = 0; i < N; i++) {
2575            ResolveInfo info = list.get(i);
2576            if (packageName.equals(info.activityInfo.packageName)) {
2577                return true;
2578            }
2579        }
2580        return false;
2581    }
2582
2583    private void checkDefaultBrowser() {
2584        final int myUserId = UserHandle.myUserId();
2585        final String packageName = getDefaultBrowserPackageName(myUserId);
2586        if (packageName != null) {
2587            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2588            if (info == null) {
2589                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2590                synchronized (mPackages) {
2591                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2592                }
2593            }
2594        }
2595    }
2596
2597    @Override
2598    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2599            throws RemoteException {
2600        try {
2601            return super.onTransact(code, data, reply, flags);
2602        } catch (RuntimeException e) {
2603            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2604                Slog.wtf(TAG, "Package Manager Crash", e);
2605            }
2606            throw e;
2607        }
2608    }
2609
2610    void cleanupInstallFailedPackage(PackageSetting ps) {
2611        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2612
2613        removeDataDirsLI(ps.volumeUuid, ps.name);
2614        if (ps.codePath != null) {
2615            if (ps.codePath.isDirectory()) {
2616                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2617            } else {
2618                ps.codePath.delete();
2619            }
2620        }
2621        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2622            if (ps.resourcePath.isDirectory()) {
2623                FileUtils.deleteContents(ps.resourcePath);
2624            }
2625            ps.resourcePath.delete();
2626        }
2627        mSettings.removePackageLPw(ps.name);
2628    }
2629
2630    static int[] appendInts(int[] cur, int[] add) {
2631        if (add == null) return cur;
2632        if (cur == null) return add;
2633        final int N = add.length;
2634        for (int i=0; i<N; i++) {
2635            cur = appendInt(cur, add[i]);
2636        }
2637        return cur;
2638    }
2639
2640    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2641        if (!sUserManager.exists(userId)) return null;
2642        final PackageSetting ps = (PackageSetting) p.mExtras;
2643        if (ps == null) {
2644            return null;
2645        }
2646
2647        final PermissionsState permissionsState = ps.getPermissionsState();
2648
2649        final int[] gids = permissionsState.computeGids(userId);
2650        final Set<String> permissions = permissionsState.getPermissions(userId);
2651        final PackageUserState state = ps.readUserState(userId);
2652
2653        return PackageParser.generatePackageInfo(p, gids, flags,
2654                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2655    }
2656
2657    @Override
2658    public boolean isPackageFrozen(String packageName) {
2659        synchronized (mPackages) {
2660            final PackageSetting ps = mSettings.mPackages.get(packageName);
2661            if (ps != null) {
2662                return ps.frozen;
2663            }
2664        }
2665        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2666        return true;
2667    }
2668
2669    @Override
2670    public boolean isPackageAvailable(String packageName, int userId) {
2671        if (!sUserManager.exists(userId)) return false;
2672        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2673        synchronized (mPackages) {
2674            PackageParser.Package p = mPackages.get(packageName);
2675            if (p != null) {
2676                final PackageSetting ps = (PackageSetting) p.mExtras;
2677                if (ps != null) {
2678                    final PackageUserState state = ps.readUserState(userId);
2679                    if (state != null) {
2680                        return PackageParser.isAvailable(state);
2681                    }
2682                }
2683            }
2684        }
2685        return false;
2686    }
2687
2688    @Override
2689    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2690        if (!sUserManager.exists(userId)) return null;
2691        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2692        // reader
2693        synchronized (mPackages) {
2694            PackageParser.Package p = mPackages.get(packageName);
2695            if (DEBUG_PACKAGE_INFO)
2696                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2697            if (p != null) {
2698                return generatePackageInfo(p, flags, userId);
2699            }
2700            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2701                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2702            }
2703        }
2704        return null;
2705    }
2706
2707    @Override
2708    public String[] currentToCanonicalPackageNames(String[] names) {
2709        String[] out = new String[names.length];
2710        // reader
2711        synchronized (mPackages) {
2712            for (int i=names.length-1; i>=0; i--) {
2713                PackageSetting ps = mSettings.mPackages.get(names[i]);
2714                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2715            }
2716        }
2717        return out;
2718    }
2719
2720    @Override
2721    public String[] canonicalToCurrentPackageNames(String[] names) {
2722        String[] out = new String[names.length];
2723        // reader
2724        synchronized (mPackages) {
2725            for (int i=names.length-1; i>=0; i--) {
2726                String cur = mSettings.mRenamedPackages.get(names[i]);
2727                out[i] = cur != null ? cur : names[i];
2728            }
2729        }
2730        return out;
2731    }
2732
2733    @Override
2734    public int getPackageUid(String packageName, int userId) {
2735        if (!sUserManager.exists(userId)) return -1;
2736        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2737
2738        // reader
2739        synchronized (mPackages) {
2740            PackageParser.Package p = mPackages.get(packageName);
2741            if(p != null) {
2742                return UserHandle.getUid(userId, p.applicationInfo.uid);
2743            }
2744            PackageSetting ps = mSettings.mPackages.get(packageName);
2745            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2746                return -1;
2747            }
2748            p = ps.pkg;
2749            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2750        }
2751    }
2752
2753    @Override
2754    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2755        if (!sUserManager.exists(userId)) {
2756            return null;
2757        }
2758
2759        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2760                "getPackageGids");
2761
2762        // reader
2763        synchronized (mPackages) {
2764            PackageParser.Package p = mPackages.get(packageName);
2765            if (DEBUG_PACKAGE_INFO) {
2766                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2767            }
2768            if (p != null) {
2769                PackageSetting ps = (PackageSetting) p.mExtras;
2770                return ps.getPermissionsState().computeGids(userId);
2771            }
2772        }
2773
2774        return null;
2775    }
2776
2777    static PermissionInfo generatePermissionInfo(
2778            BasePermission bp, int flags) {
2779        if (bp.perm != null) {
2780            return PackageParser.generatePermissionInfo(bp.perm, flags);
2781        }
2782        PermissionInfo pi = new PermissionInfo();
2783        pi.name = bp.name;
2784        pi.packageName = bp.sourcePackage;
2785        pi.nonLocalizedLabel = bp.name;
2786        pi.protectionLevel = bp.protectionLevel;
2787        return pi;
2788    }
2789
2790    @Override
2791    public PermissionInfo getPermissionInfo(String name, int flags) {
2792        // reader
2793        synchronized (mPackages) {
2794            final BasePermission p = mSettings.mPermissions.get(name);
2795            if (p != null) {
2796                return generatePermissionInfo(p, flags);
2797            }
2798            return null;
2799        }
2800    }
2801
2802    @Override
2803    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2804        // reader
2805        synchronized (mPackages) {
2806            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2807            for (BasePermission p : mSettings.mPermissions.values()) {
2808                if (group == null) {
2809                    if (p.perm == null || p.perm.info.group == null) {
2810                        out.add(generatePermissionInfo(p, flags));
2811                    }
2812                } else {
2813                    if (p.perm != null && group.equals(p.perm.info.group)) {
2814                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2815                    }
2816                }
2817            }
2818
2819            if (out.size() > 0) {
2820                return out;
2821            }
2822            return mPermissionGroups.containsKey(group) ? out : null;
2823        }
2824    }
2825
2826    @Override
2827    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2828        // reader
2829        synchronized (mPackages) {
2830            return PackageParser.generatePermissionGroupInfo(
2831                    mPermissionGroups.get(name), flags);
2832        }
2833    }
2834
2835    @Override
2836    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2837        // reader
2838        synchronized (mPackages) {
2839            final int N = mPermissionGroups.size();
2840            ArrayList<PermissionGroupInfo> out
2841                    = new ArrayList<PermissionGroupInfo>(N);
2842            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2843                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2844            }
2845            return out;
2846        }
2847    }
2848
2849    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2850            int userId) {
2851        if (!sUserManager.exists(userId)) return null;
2852        PackageSetting ps = mSettings.mPackages.get(packageName);
2853        if (ps != null) {
2854            if (ps.pkg == null) {
2855                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2856                        flags, userId);
2857                if (pInfo != null) {
2858                    return pInfo.applicationInfo;
2859                }
2860                return null;
2861            }
2862            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2863                    ps.readUserState(userId), userId);
2864        }
2865        return null;
2866    }
2867
2868    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2869            int userId) {
2870        if (!sUserManager.exists(userId)) return null;
2871        PackageSetting ps = mSettings.mPackages.get(packageName);
2872        if (ps != null) {
2873            PackageParser.Package pkg = ps.pkg;
2874            if (pkg == null) {
2875                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2876                    return null;
2877                }
2878                // Only data remains, so we aren't worried about code paths
2879                pkg = new PackageParser.Package(packageName);
2880                pkg.applicationInfo.packageName = packageName;
2881                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2882                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2883                pkg.applicationInfo.dataDir = Environment
2884                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2885                        .getAbsolutePath();
2886                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2887                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2888            }
2889            return generatePackageInfo(pkg, flags, userId);
2890        }
2891        return null;
2892    }
2893
2894    @Override
2895    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2898        // writer
2899        synchronized (mPackages) {
2900            PackageParser.Package p = mPackages.get(packageName);
2901            if (DEBUG_PACKAGE_INFO) Log.v(
2902                    TAG, "getApplicationInfo " + packageName
2903                    + ": " + p);
2904            if (p != null) {
2905                PackageSetting ps = mSettings.mPackages.get(packageName);
2906                if (ps == null) return null;
2907                // Note: isEnabledLP() does not apply here - always return info
2908                return PackageParser.generateApplicationInfo(
2909                        p, flags, ps.readUserState(userId), userId);
2910            }
2911            if ("android".equals(packageName)||"system".equals(packageName)) {
2912                return mAndroidApplication;
2913            }
2914            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2915                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2916            }
2917        }
2918        return null;
2919    }
2920
2921    @Override
2922    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2923            final IPackageDataObserver observer) {
2924        mContext.enforceCallingOrSelfPermission(
2925                android.Manifest.permission.CLEAR_APP_CACHE, null);
2926        // Queue up an async operation since clearing cache may take a little while.
2927        mHandler.post(new Runnable() {
2928            public void run() {
2929                mHandler.removeCallbacks(this);
2930                int retCode = -1;
2931                synchronized (mInstallLock) {
2932                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2933                    if (retCode < 0) {
2934                        Slog.w(TAG, "Couldn't clear application caches");
2935                    }
2936                }
2937                if (observer != null) {
2938                    try {
2939                        observer.onRemoveCompleted(null, (retCode >= 0));
2940                    } catch (RemoteException e) {
2941                        Slog.w(TAG, "RemoveException when invoking call back");
2942                    }
2943                }
2944            }
2945        });
2946    }
2947
2948    @Override
2949    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2950            final IntentSender pi) {
2951        mContext.enforceCallingOrSelfPermission(
2952                android.Manifest.permission.CLEAR_APP_CACHE, null);
2953        // Queue up an async operation since clearing cache may take a little while.
2954        mHandler.post(new Runnable() {
2955            public void run() {
2956                mHandler.removeCallbacks(this);
2957                int retCode = -1;
2958                synchronized (mInstallLock) {
2959                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2960                    if (retCode < 0) {
2961                        Slog.w(TAG, "Couldn't clear application caches");
2962                    }
2963                }
2964                if(pi != null) {
2965                    try {
2966                        // Callback via pending intent
2967                        int code = (retCode >= 0) ? 1 : 0;
2968                        pi.sendIntent(null, code, null,
2969                                null, null);
2970                    } catch (SendIntentException e1) {
2971                        Slog.i(TAG, "Failed to send pending intent");
2972                    }
2973                }
2974            }
2975        });
2976    }
2977
2978    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2979        synchronized (mInstallLock) {
2980            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2981                throw new IOException("Failed to free enough space");
2982            }
2983        }
2984    }
2985
2986    @Override
2987    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2988        if (!sUserManager.exists(userId)) return null;
2989        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2990        synchronized (mPackages) {
2991            PackageParser.Activity a = mActivities.mActivities.get(component);
2992
2993            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2994            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2995                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2996                if (ps == null) return null;
2997                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2998                        userId);
2999            }
3000            if (mResolveComponentName.equals(component)) {
3001                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3002                        new PackageUserState(), userId);
3003            }
3004        }
3005        return null;
3006    }
3007
3008    @Override
3009    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3010            String resolvedType) {
3011        synchronized (mPackages) {
3012            if (component.equals(mResolveComponentName)) {
3013                // The resolver supports EVERYTHING!
3014                return true;
3015            }
3016            PackageParser.Activity a = mActivities.mActivities.get(component);
3017            if (a == null) {
3018                return false;
3019            }
3020            for (int i=0; i<a.intents.size(); i++) {
3021                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3022                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3023                    return true;
3024                }
3025            }
3026            return false;
3027        }
3028    }
3029
3030    @Override
3031    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3032        if (!sUserManager.exists(userId)) return null;
3033        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3034        synchronized (mPackages) {
3035            PackageParser.Activity a = mReceivers.mActivities.get(component);
3036            if (DEBUG_PACKAGE_INFO) Log.v(
3037                TAG, "getReceiverInfo " + component + ": " + a);
3038            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3039                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                if (ps == null) return null;
3041                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3042                        userId);
3043            }
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3050        if (!sUserManager.exists(userId)) return null;
3051        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3052        synchronized (mPackages) {
3053            PackageParser.Service s = mServices.mServices.get(component);
3054            if (DEBUG_PACKAGE_INFO) Log.v(
3055                TAG, "getServiceInfo " + component + ": " + s);
3056            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3057                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3058                if (ps == null) return null;
3059                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3060                        userId);
3061            }
3062        }
3063        return null;
3064    }
3065
3066    @Override
3067    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3070        synchronized (mPackages) {
3071            PackageParser.Provider p = mProviders.mProviders.get(component);
3072            if (DEBUG_PACKAGE_INFO) Log.v(
3073                TAG, "getProviderInfo " + component + ": " + p);
3074            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3075                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3076                if (ps == null) return null;
3077                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3078                        userId);
3079            }
3080        }
3081        return null;
3082    }
3083
3084    @Override
3085    public String[] getSystemSharedLibraryNames() {
3086        Set<String> libSet;
3087        synchronized (mPackages) {
3088            libSet = mSharedLibraries.keySet();
3089            int size = libSet.size();
3090            if (size > 0) {
3091                String[] libs = new String[size];
3092                libSet.toArray(libs);
3093                return libs;
3094            }
3095        }
3096        return null;
3097    }
3098
3099    /**
3100     * @hide
3101     */
3102    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3103        synchronized (mPackages) {
3104            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3105            if (lib != null && lib.apk != null) {
3106                return mPackages.get(lib.apk);
3107            }
3108        }
3109        return null;
3110    }
3111
3112    @Override
3113    public FeatureInfo[] getSystemAvailableFeatures() {
3114        Collection<FeatureInfo> featSet;
3115        synchronized (mPackages) {
3116            featSet = mAvailableFeatures.values();
3117            int size = featSet.size();
3118            if (size > 0) {
3119                FeatureInfo[] features = new FeatureInfo[size+1];
3120                featSet.toArray(features);
3121                FeatureInfo fi = new FeatureInfo();
3122                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3123                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3124                features[size] = fi;
3125                return features;
3126            }
3127        }
3128        return null;
3129    }
3130
3131    @Override
3132    public boolean hasSystemFeature(String name) {
3133        synchronized (mPackages) {
3134            return mAvailableFeatures.containsKey(name);
3135        }
3136    }
3137
3138    private void checkValidCaller(int uid, int userId) {
3139        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3140            return;
3141
3142        throw new SecurityException("Caller uid=" + uid
3143                + " is not privileged to communicate with user=" + userId);
3144    }
3145
3146    @Override
3147    public int checkPermission(String permName, String pkgName, int userId) {
3148        if (!sUserManager.exists(userId)) {
3149            return PackageManager.PERMISSION_DENIED;
3150        }
3151
3152        synchronized (mPackages) {
3153            final PackageParser.Package p = mPackages.get(pkgName);
3154            if (p != null && p.mExtras != null) {
3155                final PackageSetting ps = (PackageSetting) p.mExtras;
3156                final PermissionsState permissionsState = ps.getPermissionsState();
3157                if (permissionsState.hasPermission(permName, userId)) {
3158                    return PackageManager.PERMISSION_GRANTED;
3159                }
3160                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3161                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3162                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3163                    return PackageManager.PERMISSION_GRANTED;
3164                }
3165            }
3166        }
3167
3168        return PackageManager.PERMISSION_DENIED;
3169    }
3170
3171    @Override
3172    public int checkUidPermission(String permName, int uid) {
3173        final int userId = UserHandle.getUserId(uid);
3174
3175        if (!sUserManager.exists(userId)) {
3176            return PackageManager.PERMISSION_DENIED;
3177        }
3178
3179        synchronized (mPackages) {
3180            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3181            if (obj != null) {
3182                final SettingBase ps = (SettingBase) obj;
3183                final PermissionsState permissionsState = ps.getPermissionsState();
3184                if (permissionsState.hasPermission(permName, userId)) {
3185                    return PackageManager.PERMISSION_GRANTED;
3186                }
3187                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3188                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3189                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3190                    return PackageManager.PERMISSION_GRANTED;
3191                }
3192            } else {
3193                ArraySet<String> perms = mSystemPermissions.get(uid);
3194                if (perms != null) {
3195                    if (perms.contains(permName)) {
3196                        return PackageManager.PERMISSION_GRANTED;
3197                    }
3198                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3199                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3200                        return PackageManager.PERMISSION_GRANTED;
3201                    }
3202                }
3203            }
3204        }
3205
3206        return PackageManager.PERMISSION_DENIED;
3207    }
3208
3209    @Override
3210    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3211        if (UserHandle.getCallingUserId() != userId) {
3212            mContext.enforceCallingPermission(
3213                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3214                    "isPermissionRevokedByPolicy for user " + userId);
3215        }
3216
3217        if (checkPermission(permission, packageName, userId)
3218                == PackageManager.PERMISSION_GRANTED) {
3219            return false;
3220        }
3221
3222        final long identity = Binder.clearCallingIdentity();
3223        try {
3224            final int flags = getPermissionFlags(permission, packageName, userId);
3225            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3226        } finally {
3227            Binder.restoreCallingIdentity(identity);
3228        }
3229    }
3230
3231    @Override
3232    public String getPermissionControllerPackageName() {
3233        synchronized (mPackages) {
3234            return mRequiredInstallerPackage;
3235        }
3236    }
3237
3238    /**
3239     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3240     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3241     * @param checkShell TODO(yamasani):
3242     * @param message the message to log on security exception
3243     */
3244    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3245            boolean checkShell, String message) {
3246        if (userId < 0) {
3247            throw new IllegalArgumentException("Invalid userId " + userId);
3248        }
3249        if (checkShell) {
3250            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3251        }
3252        if (userId == UserHandle.getUserId(callingUid)) return;
3253        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3254            if (requireFullPermission) {
3255                mContext.enforceCallingOrSelfPermission(
3256                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3257            } else {
3258                try {
3259                    mContext.enforceCallingOrSelfPermission(
3260                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3261                } catch (SecurityException se) {
3262                    mContext.enforceCallingOrSelfPermission(
3263                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3264                }
3265            }
3266        }
3267    }
3268
3269    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3270        if (callingUid == Process.SHELL_UID) {
3271            if (userHandle >= 0
3272                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3273                throw new SecurityException("Shell does not have permission to access user "
3274                        + userHandle);
3275            } else if (userHandle < 0) {
3276                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3277                        + Debug.getCallers(3));
3278            }
3279        }
3280    }
3281
3282    private BasePermission findPermissionTreeLP(String permName) {
3283        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3284            if (permName.startsWith(bp.name) &&
3285                    permName.length() > bp.name.length() &&
3286                    permName.charAt(bp.name.length()) == '.') {
3287                return bp;
3288            }
3289        }
3290        return null;
3291    }
3292
3293    private BasePermission checkPermissionTreeLP(String permName) {
3294        if (permName != null) {
3295            BasePermission bp = findPermissionTreeLP(permName);
3296            if (bp != null) {
3297                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3298                    return bp;
3299                }
3300                throw new SecurityException("Calling uid "
3301                        + Binder.getCallingUid()
3302                        + " is not allowed to add to permission tree "
3303                        + bp.name + " owned by uid " + bp.uid);
3304            }
3305        }
3306        throw new SecurityException("No permission tree found for " + permName);
3307    }
3308
3309    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3310        if (s1 == null) {
3311            return s2 == null;
3312        }
3313        if (s2 == null) {
3314            return false;
3315        }
3316        if (s1.getClass() != s2.getClass()) {
3317            return false;
3318        }
3319        return s1.equals(s2);
3320    }
3321
3322    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3323        if (pi1.icon != pi2.icon) return false;
3324        if (pi1.logo != pi2.logo) return false;
3325        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3326        if (!compareStrings(pi1.name, pi2.name)) return false;
3327        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3328        // We'll take care of setting this one.
3329        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3330        // These are not currently stored in settings.
3331        //if (!compareStrings(pi1.group, pi2.group)) return false;
3332        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3333        //if (pi1.labelRes != pi2.labelRes) return false;
3334        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3335        return true;
3336    }
3337
3338    int permissionInfoFootprint(PermissionInfo info) {
3339        int size = info.name.length();
3340        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3341        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3342        return size;
3343    }
3344
3345    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3346        int size = 0;
3347        for (BasePermission perm : mSettings.mPermissions.values()) {
3348            if (perm.uid == tree.uid) {
3349                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3350            }
3351        }
3352        return size;
3353    }
3354
3355    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3356        // We calculate the max size of permissions defined by this uid and throw
3357        // if that plus the size of 'info' would exceed our stated maximum.
3358        if (tree.uid != Process.SYSTEM_UID) {
3359            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3360            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3361                throw new SecurityException("Permission tree size cap exceeded");
3362            }
3363        }
3364    }
3365
3366    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3367        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3368            throw new SecurityException("Label must be specified in permission");
3369        }
3370        BasePermission tree = checkPermissionTreeLP(info.name);
3371        BasePermission bp = mSettings.mPermissions.get(info.name);
3372        boolean added = bp == null;
3373        boolean changed = true;
3374        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3375        if (added) {
3376            enforcePermissionCapLocked(info, tree);
3377            bp = new BasePermission(info.name, tree.sourcePackage,
3378                    BasePermission.TYPE_DYNAMIC);
3379        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3380            throw new SecurityException(
3381                    "Not allowed to modify non-dynamic permission "
3382                    + info.name);
3383        } else {
3384            if (bp.protectionLevel == fixedLevel
3385                    && bp.perm.owner.equals(tree.perm.owner)
3386                    && bp.uid == tree.uid
3387                    && comparePermissionInfos(bp.perm.info, info)) {
3388                changed = false;
3389            }
3390        }
3391        bp.protectionLevel = fixedLevel;
3392        info = new PermissionInfo(info);
3393        info.protectionLevel = fixedLevel;
3394        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3395        bp.perm.info.packageName = tree.perm.info.packageName;
3396        bp.uid = tree.uid;
3397        if (added) {
3398            mSettings.mPermissions.put(info.name, bp);
3399        }
3400        if (changed) {
3401            if (!async) {
3402                mSettings.writeLPr();
3403            } else {
3404                scheduleWriteSettingsLocked();
3405            }
3406        }
3407        return added;
3408    }
3409
3410    @Override
3411    public boolean addPermission(PermissionInfo info) {
3412        synchronized (mPackages) {
3413            return addPermissionLocked(info, false);
3414        }
3415    }
3416
3417    @Override
3418    public boolean addPermissionAsync(PermissionInfo info) {
3419        synchronized (mPackages) {
3420            return addPermissionLocked(info, true);
3421        }
3422    }
3423
3424    @Override
3425    public void removePermission(String name) {
3426        synchronized (mPackages) {
3427            checkPermissionTreeLP(name);
3428            BasePermission bp = mSettings.mPermissions.get(name);
3429            if (bp != null) {
3430                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3431                    throw new SecurityException(
3432                            "Not allowed to modify non-dynamic permission "
3433                            + name);
3434                }
3435                mSettings.mPermissions.remove(name);
3436                mSettings.writeLPr();
3437            }
3438        }
3439    }
3440
3441    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3442            BasePermission bp) {
3443        int index = pkg.requestedPermissions.indexOf(bp.name);
3444        if (index == -1) {
3445            throw new SecurityException("Package " + pkg.packageName
3446                    + " has not requested permission " + bp.name);
3447        }
3448        if (!bp.isRuntime() && !bp.isDevelopment()) {
3449            throw new SecurityException("Permission " + bp.name
3450                    + " is not a changeable permission type");
3451        }
3452    }
3453
3454    @Override
3455    public void grantRuntimePermission(String packageName, String name, final int userId) {
3456        if (!sUserManager.exists(userId)) {
3457            Log.e(TAG, "No such user:" + userId);
3458            return;
3459        }
3460
3461        mContext.enforceCallingOrSelfPermission(
3462                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3463                "grantRuntimePermission");
3464
3465        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3466                "grantRuntimePermission");
3467
3468        final int uid;
3469        final SettingBase sb;
3470
3471        synchronized (mPackages) {
3472            final PackageParser.Package pkg = mPackages.get(packageName);
3473            if (pkg == null) {
3474                throw new IllegalArgumentException("Unknown package: " + packageName);
3475            }
3476
3477            final BasePermission bp = mSettings.mPermissions.get(name);
3478            if (bp == null) {
3479                throw new IllegalArgumentException("Unknown permission: " + name);
3480            }
3481
3482            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3483
3484            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3485            sb = (SettingBase) pkg.mExtras;
3486            if (sb == null) {
3487                throw new IllegalArgumentException("Unknown package: " + packageName);
3488            }
3489
3490            final PermissionsState permissionsState = sb.getPermissionsState();
3491
3492            final int flags = permissionsState.getPermissionFlags(name, userId);
3493            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3494                throw new SecurityException("Cannot grant system fixed permission: "
3495                        + name + " for package: " + packageName);
3496            }
3497
3498            if (bp.isDevelopment()) {
3499                // Development permissions must be handled specially, since they are not
3500                // normal runtime permissions.  For now they apply to all users.
3501                if (permissionsState.grantInstallPermission(bp) !=
3502                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3503                    scheduleWriteSettingsLocked();
3504                }
3505                return;
3506            }
3507
3508            final int result = permissionsState.grantRuntimePermission(bp, userId);
3509            switch (result) {
3510                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3511                    return;
3512                }
3513
3514                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3515                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3516                    mHandler.post(new Runnable() {
3517                        @Override
3518                        public void run() {
3519                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3520                        }
3521                    });
3522                } break;
3523            }
3524
3525            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3526
3527            // Not critical if that is lost - app has to request again.
3528            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3529        }
3530
3531        // Only need to do this if user is initialized. Otherwise it's a new user
3532        // and there are no processes running as the user yet and there's no need
3533        // to make an expensive call to remount processes for the changed permissions.
3534        if (READ_EXTERNAL_STORAGE.equals(name)
3535                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3536            final long token = Binder.clearCallingIdentity();
3537            try {
3538                if (sUserManager.isInitialized(userId)) {
3539                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3540                            MountServiceInternal.class);
3541                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3542                }
3543            } finally {
3544                Binder.restoreCallingIdentity(token);
3545            }
3546        }
3547    }
3548
3549    @Override
3550    public void revokeRuntimePermission(String packageName, String name, int userId) {
3551        if (!sUserManager.exists(userId)) {
3552            Log.e(TAG, "No such user:" + userId);
3553            return;
3554        }
3555
3556        mContext.enforceCallingOrSelfPermission(
3557                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3558                "revokeRuntimePermission");
3559
3560        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3561                "revokeRuntimePermission");
3562
3563        final int appId;
3564
3565        synchronized (mPackages) {
3566            final PackageParser.Package pkg = mPackages.get(packageName);
3567            if (pkg == null) {
3568                throw new IllegalArgumentException("Unknown package: " + packageName);
3569            }
3570
3571            final BasePermission bp = mSettings.mPermissions.get(name);
3572            if (bp == null) {
3573                throw new IllegalArgumentException("Unknown permission: " + name);
3574            }
3575
3576            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3577
3578            SettingBase sb = (SettingBase) pkg.mExtras;
3579            if (sb == null) {
3580                throw new IllegalArgumentException("Unknown package: " + packageName);
3581            }
3582
3583            final PermissionsState permissionsState = sb.getPermissionsState();
3584
3585            final int flags = permissionsState.getPermissionFlags(name, userId);
3586            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3587                throw new SecurityException("Cannot revoke system fixed permission: "
3588                        + name + " for package: " + packageName);
3589            }
3590
3591            if (bp.isDevelopment()) {
3592                // Development permissions must be handled specially, since they are not
3593                // normal runtime permissions.  For now they apply to all users.
3594                if (permissionsState.revokeInstallPermission(bp) !=
3595                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3596                    scheduleWriteSettingsLocked();
3597                }
3598                return;
3599            }
3600
3601            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3602                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3603                return;
3604            }
3605
3606            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3607
3608            // Critical, after this call app should never have the permission.
3609            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3610
3611            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3612        }
3613
3614        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3615    }
3616
3617    @Override
3618    public void resetRuntimePermissions() {
3619        mContext.enforceCallingOrSelfPermission(
3620                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3621                "revokeRuntimePermission");
3622
3623        int callingUid = Binder.getCallingUid();
3624        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3625            mContext.enforceCallingOrSelfPermission(
3626                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3627                    "resetRuntimePermissions");
3628        }
3629
3630        synchronized (mPackages) {
3631            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3632            for (int userId : UserManagerService.getInstance().getUserIds()) {
3633                final int packageCount = mPackages.size();
3634                for (int i = 0; i < packageCount; i++) {
3635                    PackageParser.Package pkg = mPackages.valueAt(i);
3636                    if (!(pkg.mExtras instanceof PackageSetting)) {
3637                        continue;
3638                    }
3639                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3640                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3641                }
3642            }
3643        }
3644    }
3645
3646    @Override
3647    public int getPermissionFlags(String name, String packageName, int userId) {
3648        if (!sUserManager.exists(userId)) {
3649            return 0;
3650        }
3651
3652        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3653
3654        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3655                "getPermissionFlags");
3656
3657        synchronized (mPackages) {
3658            final PackageParser.Package pkg = mPackages.get(packageName);
3659            if (pkg == null) {
3660                throw new IllegalArgumentException("Unknown package: " + packageName);
3661            }
3662
3663            final BasePermission bp = mSettings.mPermissions.get(name);
3664            if (bp == null) {
3665                throw new IllegalArgumentException("Unknown permission: " + name);
3666            }
3667
3668            SettingBase sb = (SettingBase) pkg.mExtras;
3669            if (sb == null) {
3670                throw new IllegalArgumentException("Unknown package: " + packageName);
3671            }
3672
3673            PermissionsState permissionsState = sb.getPermissionsState();
3674            return permissionsState.getPermissionFlags(name, userId);
3675        }
3676    }
3677
3678    @Override
3679    public void updatePermissionFlags(String name, String packageName, int flagMask,
3680            int flagValues, int userId) {
3681        if (!sUserManager.exists(userId)) {
3682            return;
3683        }
3684
3685        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3686
3687        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3688                "updatePermissionFlags");
3689
3690        // Only the system can change these flags and nothing else.
3691        if (getCallingUid() != Process.SYSTEM_UID) {
3692            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3694            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3696        }
3697
3698        synchronized (mPackages) {
3699            final PackageParser.Package pkg = mPackages.get(packageName);
3700            if (pkg == null) {
3701                throw new IllegalArgumentException("Unknown package: " + packageName);
3702            }
3703
3704            final BasePermission bp = mSettings.mPermissions.get(name);
3705            if (bp == null) {
3706                throw new IllegalArgumentException("Unknown permission: " + name);
3707            }
3708
3709            SettingBase sb = (SettingBase) pkg.mExtras;
3710            if (sb == null) {
3711                throw new IllegalArgumentException("Unknown package: " + packageName);
3712            }
3713
3714            PermissionsState permissionsState = sb.getPermissionsState();
3715
3716            // Only the package manager can change flags for system component permissions.
3717            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3718            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3719                return;
3720            }
3721
3722            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3723
3724            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3725                // Install and runtime permissions are stored in different places,
3726                // so figure out what permission changed and persist the change.
3727                if (permissionsState.getInstallPermissionState(name) != null) {
3728                    scheduleWriteSettingsLocked();
3729                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3730                        || hadState) {
3731                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3732                }
3733            }
3734        }
3735    }
3736
3737    /**
3738     * Update the permission flags for all packages and runtime permissions of a user in order
3739     * to allow device or profile owner to remove POLICY_FIXED.
3740     */
3741    @Override
3742    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3743        if (!sUserManager.exists(userId)) {
3744            return;
3745        }
3746
3747        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3748
3749        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3750                "updatePermissionFlagsForAllApps");
3751
3752        // Only the system can change system fixed flags.
3753        if (getCallingUid() != Process.SYSTEM_UID) {
3754            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3756        }
3757
3758        synchronized (mPackages) {
3759            boolean changed = false;
3760            final int packageCount = mPackages.size();
3761            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3762                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3763                SettingBase sb = (SettingBase) pkg.mExtras;
3764                if (sb == null) {
3765                    continue;
3766                }
3767                PermissionsState permissionsState = sb.getPermissionsState();
3768                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3769                        userId, flagMask, flagValues);
3770            }
3771            if (changed) {
3772                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3773            }
3774        }
3775    }
3776
3777    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3778        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3779                != PackageManager.PERMISSION_GRANTED
3780            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3781                != PackageManager.PERMISSION_GRANTED) {
3782            throw new SecurityException(message + " requires "
3783                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3784                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3785        }
3786    }
3787
3788    @Override
3789    public boolean shouldShowRequestPermissionRationale(String permissionName,
3790            String packageName, int userId) {
3791        if (UserHandle.getCallingUserId() != userId) {
3792            mContext.enforceCallingPermission(
3793                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3794                    "canShowRequestPermissionRationale for user " + userId);
3795        }
3796
3797        final int uid = getPackageUid(packageName, userId);
3798        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3799            return false;
3800        }
3801
3802        if (checkPermission(permissionName, packageName, userId)
3803                == PackageManager.PERMISSION_GRANTED) {
3804            return false;
3805        }
3806
3807        final int flags;
3808
3809        final long identity = Binder.clearCallingIdentity();
3810        try {
3811            flags = getPermissionFlags(permissionName,
3812                    packageName, userId);
3813        } finally {
3814            Binder.restoreCallingIdentity(identity);
3815        }
3816
3817        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3818                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3819                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3820
3821        if ((flags & fixedFlags) != 0) {
3822            return false;
3823        }
3824
3825        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3826    }
3827
3828    @Override
3829    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3830        mContext.enforceCallingOrSelfPermission(
3831                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3832                "addOnPermissionsChangeListener");
3833
3834        synchronized (mPackages) {
3835            mOnPermissionChangeListeners.addListenerLocked(listener);
3836        }
3837    }
3838
3839    @Override
3840    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3841        synchronized (mPackages) {
3842            mOnPermissionChangeListeners.removeListenerLocked(listener);
3843        }
3844    }
3845
3846    @Override
3847    public boolean isProtectedBroadcast(String actionName) {
3848        synchronized (mPackages) {
3849            return mProtectedBroadcasts.contains(actionName);
3850        }
3851    }
3852
3853    @Override
3854    public int checkSignatures(String pkg1, String pkg2) {
3855        synchronized (mPackages) {
3856            final PackageParser.Package p1 = mPackages.get(pkg1);
3857            final PackageParser.Package p2 = mPackages.get(pkg2);
3858            if (p1 == null || p1.mExtras == null
3859                    || p2 == null || p2.mExtras == null) {
3860                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3861            }
3862            return compareSignatures(p1.mSignatures, p2.mSignatures);
3863        }
3864    }
3865
3866    @Override
3867    public int checkUidSignatures(int uid1, int uid2) {
3868        // Map to base uids.
3869        uid1 = UserHandle.getAppId(uid1);
3870        uid2 = UserHandle.getAppId(uid2);
3871        // reader
3872        synchronized (mPackages) {
3873            Signature[] s1;
3874            Signature[] s2;
3875            Object obj = mSettings.getUserIdLPr(uid1);
3876            if (obj != null) {
3877                if (obj instanceof SharedUserSetting) {
3878                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3879                } else if (obj instanceof PackageSetting) {
3880                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3881                } else {
3882                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3883                }
3884            } else {
3885                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3886            }
3887            obj = mSettings.getUserIdLPr(uid2);
3888            if (obj != null) {
3889                if (obj instanceof SharedUserSetting) {
3890                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3891                } else if (obj instanceof PackageSetting) {
3892                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3893                } else {
3894                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3895                }
3896            } else {
3897                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3898            }
3899            return compareSignatures(s1, s2);
3900        }
3901    }
3902
3903    private void killUid(int appId, int userId, String reason) {
3904        final long identity = Binder.clearCallingIdentity();
3905        try {
3906            IActivityManager am = ActivityManagerNative.getDefault();
3907            if (am != null) {
3908                try {
3909                    am.killUid(appId, userId, reason);
3910                } catch (RemoteException e) {
3911                    /* ignore - same process */
3912                }
3913            }
3914        } finally {
3915            Binder.restoreCallingIdentity(identity);
3916        }
3917    }
3918
3919    /**
3920     * Compares two sets of signatures. Returns:
3921     * <br />
3922     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3923     * <br />
3924     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3925     * <br />
3926     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3927     * <br />
3928     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3929     * <br />
3930     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3931     */
3932    static int compareSignatures(Signature[] s1, Signature[] s2) {
3933        if (s1 == null) {
3934            return s2 == null
3935                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3936                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3937        }
3938
3939        if (s2 == null) {
3940            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3941        }
3942
3943        if (s1.length != s2.length) {
3944            return PackageManager.SIGNATURE_NO_MATCH;
3945        }
3946
3947        // Since both signature sets are of size 1, we can compare without HashSets.
3948        if (s1.length == 1) {
3949            return s1[0].equals(s2[0]) ?
3950                    PackageManager.SIGNATURE_MATCH :
3951                    PackageManager.SIGNATURE_NO_MATCH;
3952        }
3953
3954        ArraySet<Signature> set1 = new ArraySet<Signature>();
3955        for (Signature sig : s1) {
3956            set1.add(sig);
3957        }
3958        ArraySet<Signature> set2 = new ArraySet<Signature>();
3959        for (Signature sig : s2) {
3960            set2.add(sig);
3961        }
3962        // Make sure s2 contains all signatures in s1.
3963        if (set1.equals(set2)) {
3964            return PackageManager.SIGNATURE_MATCH;
3965        }
3966        return PackageManager.SIGNATURE_NO_MATCH;
3967    }
3968
3969    /**
3970     * If the database version for this type of package (internal storage or
3971     * external storage) is less than the version where package signatures
3972     * were updated, return true.
3973     */
3974    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3975        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3976        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3977    }
3978
3979    /**
3980     * Used for backward compatibility to make sure any packages with
3981     * certificate chains get upgraded to the new style. {@code existingSigs}
3982     * will be in the old format (since they were stored on disk from before the
3983     * system upgrade) and {@code scannedSigs} will be in the newer format.
3984     */
3985    private int compareSignaturesCompat(PackageSignatures existingSigs,
3986            PackageParser.Package scannedPkg) {
3987        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3988            return PackageManager.SIGNATURE_NO_MATCH;
3989        }
3990
3991        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3992        for (Signature sig : existingSigs.mSignatures) {
3993            existingSet.add(sig);
3994        }
3995        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3996        for (Signature sig : scannedPkg.mSignatures) {
3997            try {
3998                Signature[] chainSignatures = sig.getChainSignatures();
3999                for (Signature chainSig : chainSignatures) {
4000                    scannedCompatSet.add(chainSig);
4001                }
4002            } catch (CertificateEncodingException e) {
4003                scannedCompatSet.add(sig);
4004            }
4005        }
4006        /*
4007         * Make sure the expanded scanned set contains all signatures in the
4008         * existing one.
4009         */
4010        if (scannedCompatSet.equals(existingSet)) {
4011            // Migrate the old signatures to the new scheme.
4012            existingSigs.assignSignatures(scannedPkg.mSignatures);
4013            // The new KeySets will be re-added later in the scanning process.
4014            synchronized (mPackages) {
4015                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4016            }
4017            return PackageManager.SIGNATURE_MATCH;
4018        }
4019        return PackageManager.SIGNATURE_NO_MATCH;
4020    }
4021
4022    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4023        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4024        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4025    }
4026
4027    private int compareSignaturesRecover(PackageSignatures existingSigs,
4028            PackageParser.Package scannedPkg) {
4029        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4030            return PackageManager.SIGNATURE_NO_MATCH;
4031        }
4032
4033        String msg = null;
4034        try {
4035            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4036                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4037                        + scannedPkg.packageName);
4038                return PackageManager.SIGNATURE_MATCH;
4039            }
4040        } catch (CertificateException e) {
4041            msg = e.getMessage();
4042        }
4043
4044        logCriticalInfo(Log.INFO,
4045                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4046        return PackageManager.SIGNATURE_NO_MATCH;
4047    }
4048
4049    @Override
4050    public String[] getPackagesForUid(int uid) {
4051        uid = UserHandle.getAppId(uid);
4052        // reader
4053        synchronized (mPackages) {
4054            Object obj = mSettings.getUserIdLPr(uid);
4055            if (obj instanceof SharedUserSetting) {
4056                final SharedUserSetting sus = (SharedUserSetting) obj;
4057                final int N = sus.packages.size();
4058                final String[] res = new String[N];
4059                final Iterator<PackageSetting> it = sus.packages.iterator();
4060                int i = 0;
4061                while (it.hasNext()) {
4062                    res[i++] = it.next().name;
4063                }
4064                return res;
4065            } else if (obj instanceof PackageSetting) {
4066                final PackageSetting ps = (PackageSetting) obj;
4067                return new String[] { ps.name };
4068            }
4069        }
4070        return null;
4071    }
4072
4073    @Override
4074    public String getNameForUid(int uid) {
4075        // reader
4076        synchronized (mPackages) {
4077            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4078            if (obj instanceof SharedUserSetting) {
4079                final SharedUserSetting sus = (SharedUserSetting) obj;
4080                return sus.name + ":" + sus.userId;
4081            } else if (obj instanceof PackageSetting) {
4082                final PackageSetting ps = (PackageSetting) obj;
4083                return ps.name;
4084            }
4085        }
4086        return null;
4087    }
4088
4089    @Override
4090    public int getUidForSharedUser(String sharedUserName) {
4091        if(sharedUserName == null) {
4092            return -1;
4093        }
4094        // reader
4095        synchronized (mPackages) {
4096            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4097            if (suid == null) {
4098                return -1;
4099            }
4100            return suid.userId;
4101        }
4102    }
4103
4104    @Override
4105    public int getFlagsForUid(int uid) {
4106        synchronized (mPackages) {
4107            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4108            if (obj instanceof SharedUserSetting) {
4109                final SharedUserSetting sus = (SharedUserSetting) obj;
4110                return sus.pkgFlags;
4111            } else if (obj instanceof PackageSetting) {
4112                final PackageSetting ps = (PackageSetting) obj;
4113                return ps.pkgFlags;
4114            }
4115        }
4116        return 0;
4117    }
4118
4119    @Override
4120    public int getPrivateFlagsForUid(int uid) {
4121        synchronized (mPackages) {
4122            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4123            if (obj instanceof SharedUserSetting) {
4124                final SharedUserSetting sus = (SharedUserSetting) obj;
4125                return sus.pkgPrivateFlags;
4126            } else if (obj instanceof PackageSetting) {
4127                final PackageSetting ps = (PackageSetting) obj;
4128                return ps.pkgPrivateFlags;
4129            }
4130        }
4131        return 0;
4132    }
4133
4134    @Override
4135    public boolean isUidPrivileged(int uid) {
4136        uid = UserHandle.getAppId(uid);
4137        // reader
4138        synchronized (mPackages) {
4139            Object obj = mSettings.getUserIdLPr(uid);
4140            if (obj instanceof SharedUserSetting) {
4141                final SharedUserSetting sus = (SharedUserSetting) obj;
4142                final Iterator<PackageSetting> it = sus.packages.iterator();
4143                while (it.hasNext()) {
4144                    if (it.next().isPrivileged()) {
4145                        return true;
4146                    }
4147                }
4148            } else if (obj instanceof PackageSetting) {
4149                final PackageSetting ps = (PackageSetting) obj;
4150                return ps.isPrivileged();
4151            }
4152        }
4153        return false;
4154    }
4155
4156    @Override
4157    public String[] getAppOpPermissionPackages(String permissionName) {
4158        synchronized (mPackages) {
4159            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4160            if (pkgs == null) {
4161                return null;
4162            }
4163            return pkgs.toArray(new String[pkgs.size()]);
4164        }
4165    }
4166
4167    @Override
4168    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4169            int flags, int userId) {
4170        if (!sUserManager.exists(userId)) return null;
4171        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4172        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4173        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4174    }
4175
4176    @Override
4177    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4178            IntentFilter filter, int match, ComponentName activity) {
4179        final int userId = UserHandle.getCallingUserId();
4180        if (DEBUG_PREFERRED) {
4181            Log.v(TAG, "setLastChosenActivity intent=" + intent
4182                + " resolvedType=" + resolvedType
4183                + " flags=" + flags
4184                + " filter=" + filter
4185                + " match=" + match
4186                + " activity=" + activity);
4187            filter.dump(new PrintStreamPrinter(System.out), "    ");
4188        }
4189        intent.setComponent(null);
4190        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4191        // Find any earlier preferred or last chosen entries and nuke them
4192        findPreferredActivity(intent, resolvedType,
4193                flags, query, 0, false, true, false, userId);
4194        // Add the new activity as the last chosen for this filter
4195        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4196                "Setting last chosen");
4197    }
4198
4199    @Override
4200    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4201        final int userId = UserHandle.getCallingUserId();
4202        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4203        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4204        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4205                false, false, false, userId);
4206    }
4207
4208    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4209            int flags, List<ResolveInfo> query, int userId) {
4210        if (query != null) {
4211            final int N = query.size();
4212            if (N == 1) {
4213                return query.get(0);
4214            } else if (N > 1) {
4215                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4216                // If there is more than one activity with the same priority,
4217                // then let the user decide between them.
4218                ResolveInfo r0 = query.get(0);
4219                ResolveInfo r1 = query.get(1);
4220                if (DEBUG_INTENT_MATCHING || debug) {
4221                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4222                            + r1.activityInfo.name + "=" + r1.priority);
4223                }
4224                // If the first activity has a higher priority, or a different
4225                // default, then it is always desireable to pick it.
4226                if (r0.priority != r1.priority
4227                        || r0.preferredOrder != r1.preferredOrder
4228                        || r0.isDefault != r1.isDefault) {
4229                    return query.get(0);
4230                }
4231                // If we have saved a preference for a preferred activity for
4232                // this Intent, use that.
4233                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4234                        flags, query, r0.priority, true, false, debug, userId);
4235                if (ri != null) {
4236                    return ri;
4237                }
4238                ri = new ResolveInfo(mResolveInfo);
4239                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4240                ri.activityInfo.applicationInfo = new ApplicationInfo(
4241                        ri.activityInfo.applicationInfo);
4242                if (userId != 0) {
4243                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4244                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4245                }
4246                // Make sure that the resolver is displayable in car mode
4247                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4248                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4249                return ri;
4250            }
4251        }
4252        return null;
4253    }
4254
4255    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4256            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4257        final int N = query.size();
4258        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4259                .get(userId);
4260        // Get the list of persistent preferred activities that handle the intent
4261        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4262        List<PersistentPreferredActivity> pprefs = ppir != null
4263                ? ppir.queryIntent(intent, resolvedType,
4264                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4265                : null;
4266        if (pprefs != null && pprefs.size() > 0) {
4267            final int M = pprefs.size();
4268            for (int i=0; i<M; i++) {
4269                final PersistentPreferredActivity ppa = pprefs.get(i);
4270                if (DEBUG_PREFERRED || debug) {
4271                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4272                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4273                            + "\n  component=" + ppa.mComponent);
4274                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4275                }
4276                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4277                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4278                if (DEBUG_PREFERRED || debug) {
4279                    Slog.v(TAG, "Found persistent preferred activity:");
4280                    if (ai != null) {
4281                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4282                    } else {
4283                        Slog.v(TAG, "  null");
4284                    }
4285                }
4286                if (ai == null) {
4287                    // This previously registered persistent preferred activity
4288                    // component is no longer known. Ignore it and do NOT remove it.
4289                    continue;
4290                }
4291                for (int j=0; j<N; j++) {
4292                    final ResolveInfo ri = query.get(j);
4293                    if (!ri.activityInfo.applicationInfo.packageName
4294                            .equals(ai.applicationInfo.packageName)) {
4295                        continue;
4296                    }
4297                    if (!ri.activityInfo.name.equals(ai.name)) {
4298                        continue;
4299                    }
4300                    //  Found a persistent preference that can handle the intent.
4301                    if (DEBUG_PREFERRED || debug) {
4302                        Slog.v(TAG, "Returning persistent preferred activity: " +
4303                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4304                    }
4305                    return ri;
4306                }
4307            }
4308        }
4309        return null;
4310    }
4311
4312    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4313            List<ResolveInfo> query, int priority, boolean always,
4314            boolean removeMatches, boolean debug, int userId) {
4315        if (!sUserManager.exists(userId)) return null;
4316        // writer
4317        synchronized (mPackages) {
4318            if (intent.getSelector() != null) {
4319                intent = intent.getSelector();
4320            }
4321            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4322
4323            // Try to find a matching persistent preferred activity.
4324            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4325                    debug, userId);
4326
4327            // If a persistent preferred activity matched, use it.
4328            if (pri != null) {
4329                return pri;
4330            }
4331
4332            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4333            // Get the list of preferred activities that handle the intent
4334            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4335            List<PreferredActivity> prefs = pir != null
4336                    ? pir.queryIntent(intent, resolvedType,
4337                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4338                    : null;
4339            if (prefs != null && prefs.size() > 0) {
4340                boolean changed = false;
4341                try {
4342                    // First figure out how good the original match set is.
4343                    // We will only allow preferred activities that came
4344                    // from the same match quality.
4345                    int match = 0;
4346
4347                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4348
4349                    final int N = query.size();
4350                    for (int j=0; j<N; j++) {
4351                        final ResolveInfo ri = query.get(j);
4352                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4353                                + ": 0x" + Integer.toHexString(match));
4354                        if (ri.match > match) {
4355                            match = ri.match;
4356                        }
4357                    }
4358
4359                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4360                            + Integer.toHexString(match));
4361
4362                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4363                    final int M = prefs.size();
4364                    for (int i=0; i<M; i++) {
4365                        final PreferredActivity pa = prefs.get(i);
4366                        if (DEBUG_PREFERRED || debug) {
4367                            Slog.v(TAG, "Checking PreferredActivity ds="
4368                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4369                                    + "\n  component=" + pa.mPref.mComponent);
4370                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4371                        }
4372                        if (pa.mPref.mMatch != match) {
4373                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4374                                    + Integer.toHexString(pa.mPref.mMatch));
4375                            continue;
4376                        }
4377                        // If it's not an "always" type preferred activity and that's what we're
4378                        // looking for, skip it.
4379                        if (always && !pa.mPref.mAlways) {
4380                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4381                            continue;
4382                        }
4383                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4384                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4385                        if (DEBUG_PREFERRED || debug) {
4386                            Slog.v(TAG, "Found preferred activity:");
4387                            if (ai != null) {
4388                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4389                            } else {
4390                                Slog.v(TAG, "  null");
4391                            }
4392                        }
4393                        if (ai == null) {
4394                            // This previously registered preferred activity
4395                            // component is no longer known.  Most likely an update
4396                            // to the app was installed and in the new version this
4397                            // component no longer exists.  Clean it up by removing
4398                            // it from the preferred activities list, and skip it.
4399                            Slog.w(TAG, "Removing dangling preferred activity: "
4400                                    + pa.mPref.mComponent);
4401                            pir.removeFilter(pa);
4402                            changed = true;
4403                            continue;
4404                        }
4405                        for (int j=0; j<N; j++) {
4406                            final ResolveInfo ri = query.get(j);
4407                            if (!ri.activityInfo.applicationInfo.packageName
4408                                    .equals(ai.applicationInfo.packageName)) {
4409                                continue;
4410                            }
4411                            if (!ri.activityInfo.name.equals(ai.name)) {
4412                                continue;
4413                            }
4414
4415                            if (removeMatches) {
4416                                pir.removeFilter(pa);
4417                                changed = true;
4418                                if (DEBUG_PREFERRED) {
4419                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4420                                }
4421                                break;
4422                            }
4423
4424                            // Okay we found a previously set preferred or last chosen app.
4425                            // If the result set is different from when this
4426                            // was created, we need to clear it and re-ask the
4427                            // user their preference, if we're looking for an "always" type entry.
4428                            if (always && !pa.mPref.sameSet(query)) {
4429                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4430                                        + intent + " type " + resolvedType);
4431                                if (DEBUG_PREFERRED) {
4432                                    Slog.v(TAG, "Removing preferred activity since set changed "
4433                                            + pa.mPref.mComponent);
4434                                }
4435                                pir.removeFilter(pa);
4436                                // Re-add the filter as a "last chosen" entry (!always)
4437                                PreferredActivity lastChosen = new PreferredActivity(
4438                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4439                                pir.addFilter(lastChosen);
4440                                changed = true;
4441                                return null;
4442                            }
4443
4444                            // Yay! Either the set matched or we're looking for the last chosen
4445                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4446                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4447                            return ri;
4448                        }
4449                    }
4450                } finally {
4451                    if (changed) {
4452                        if (DEBUG_PREFERRED) {
4453                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4454                        }
4455                        scheduleWritePackageRestrictionsLocked(userId);
4456                    }
4457                }
4458            }
4459        }
4460        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4461        return null;
4462    }
4463
4464    /*
4465     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4466     */
4467    @Override
4468    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4469            int targetUserId) {
4470        mContext.enforceCallingOrSelfPermission(
4471                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4472        List<CrossProfileIntentFilter> matches =
4473                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4474        if (matches != null) {
4475            int size = matches.size();
4476            for (int i = 0; i < size; i++) {
4477                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4478            }
4479        }
4480        if (hasWebURI(intent)) {
4481            // cross-profile app linking works only towards the parent.
4482            final UserInfo parent = getProfileParent(sourceUserId);
4483            synchronized(mPackages) {
4484                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4485                        intent, resolvedType, 0, sourceUserId, parent.id);
4486                return xpDomainInfo != null;
4487            }
4488        }
4489        return false;
4490    }
4491
4492    private UserInfo getProfileParent(int userId) {
4493        final long identity = Binder.clearCallingIdentity();
4494        try {
4495            return sUserManager.getProfileParent(userId);
4496        } finally {
4497            Binder.restoreCallingIdentity(identity);
4498        }
4499    }
4500
4501    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4502            String resolvedType, int userId) {
4503        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4504        if (resolver != null) {
4505            return resolver.queryIntent(intent, resolvedType, false, userId);
4506        }
4507        return null;
4508    }
4509
4510    @Override
4511    public List<ResolveInfo> queryIntentActivities(Intent intent,
4512            String resolvedType, int flags, int userId) {
4513        if (!sUserManager.exists(userId)) return Collections.emptyList();
4514        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4515        ComponentName comp = intent.getComponent();
4516        if (comp == null) {
4517            if (intent.getSelector() != null) {
4518                intent = intent.getSelector();
4519                comp = intent.getComponent();
4520            }
4521        }
4522
4523        if (comp != null) {
4524            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4525            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4526            if (ai != null) {
4527                final ResolveInfo ri = new ResolveInfo();
4528                ri.activityInfo = ai;
4529                list.add(ri);
4530            }
4531            return list;
4532        }
4533
4534        // reader
4535        synchronized (mPackages) {
4536            final String pkgName = intent.getPackage();
4537            if (pkgName == null) {
4538                List<CrossProfileIntentFilter> matchingFilters =
4539                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4540                // Check for results that need to skip the current profile.
4541                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4542                        resolvedType, flags, userId);
4543                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4544                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4545                    result.add(xpResolveInfo);
4546                    return filterIfNotPrimaryUser(result, userId);
4547                }
4548
4549                // Check for results in the current profile.
4550                List<ResolveInfo> result = mActivities.queryIntent(
4551                        intent, resolvedType, flags, userId);
4552
4553                // Check for cross profile results.
4554                xpResolveInfo = queryCrossProfileIntents(
4555                        matchingFilters, intent, resolvedType, flags, userId);
4556                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4557                    result.add(xpResolveInfo);
4558                    Collections.sort(result, mResolvePrioritySorter);
4559                }
4560                result = filterIfNotPrimaryUser(result, userId);
4561                if (hasWebURI(intent)) {
4562                    CrossProfileDomainInfo xpDomainInfo = null;
4563                    final UserInfo parent = getProfileParent(userId);
4564                    if (parent != null) {
4565                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4566                                flags, userId, parent.id);
4567                    }
4568                    if (xpDomainInfo != null) {
4569                        if (xpResolveInfo != null) {
4570                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4571                            // in the result.
4572                            result.remove(xpResolveInfo);
4573                        }
4574                        if (result.size() == 0) {
4575                            result.add(xpDomainInfo.resolveInfo);
4576                            return result;
4577                        }
4578                    } else if (result.size() <= 1) {
4579                        return result;
4580                    }
4581                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4582                            xpDomainInfo, userId);
4583                    Collections.sort(result, mResolvePrioritySorter);
4584                }
4585                return result;
4586            }
4587            final PackageParser.Package pkg = mPackages.get(pkgName);
4588            if (pkg != null) {
4589                return filterIfNotPrimaryUser(
4590                        mActivities.queryIntentForPackage(
4591                                intent, resolvedType, flags, pkg.activities, userId),
4592                        userId);
4593            }
4594            return new ArrayList<ResolveInfo>();
4595        }
4596    }
4597
4598    private static class CrossProfileDomainInfo {
4599        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4600        ResolveInfo resolveInfo;
4601        /* Best domain verification status of the activities found in the other profile */
4602        int bestDomainVerificationStatus;
4603    }
4604
4605    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4606            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4607        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4608                sourceUserId)) {
4609            return null;
4610        }
4611        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4612                resolvedType, flags, parentUserId);
4613
4614        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4615            return null;
4616        }
4617        CrossProfileDomainInfo result = null;
4618        int size = resultTargetUser.size();
4619        for (int i = 0; i < size; i++) {
4620            ResolveInfo riTargetUser = resultTargetUser.get(i);
4621            // Intent filter verification is only for filters that specify a host. So don't return
4622            // those that handle all web uris.
4623            if (riTargetUser.handleAllWebDataURI) {
4624                continue;
4625            }
4626            String packageName = riTargetUser.activityInfo.packageName;
4627            PackageSetting ps = mSettings.mPackages.get(packageName);
4628            if (ps == null) {
4629                continue;
4630            }
4631            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4632            int status = (int)(verificationState >> 32);
4633            if (result == null) {
4634                result = new CrossProfileDomainInfo();
4635                result.resolveInfo =
4636                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4637                result.bestDomainVerificationStatus = status;
4638            } else {
4639                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4640                        result.bestDomainVerificationStatus);
4641            }
4642        }
4643        // Don't consider matches with status NEVER across profiles.
4644        if (result != null && result.bestDomainVerificationStatus
4645                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4646            return null;
4647        }
4648        return result;
4649    }
4650
4651    /**
4652     * Verification statuses are ordered from the worse to the best, except for
4653     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4654     */
4655    private int bestDomainVerificationStatus(int status1, int status2) {
4656        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4657            return status2;
4658        }
4659        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4660            return status1;
4661        }
4662        return (int) MathUtils.max(status1, status2);
4663    }
4664
4665    private boolean isUserEnabled(int userId) {
4666        long callingId = Binder.clearCallingIdentity();
4667        try {
4668            UserInfo userInfo = sUserManager.getUserInfo(userId);
4669            return userInfo != null && userInfo.isEnabled();
4670        } finally {
4671            Binder.restoreCallingIdentity(callingId);
4672        }
4673    }
4674
4675    /**
4676     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4677     *
4678     * @return filtered list
4679     */
4680    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4681        if (userId == UserHandle.USER_OWNER) {
4682            return resolveInfos;
4683        }
4684        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4685            ResolveInfo info = resolveInfos.get(i);
4686            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4687                resolveInfos.remove(i);
4688            }
4689        }
4690        return resolveInfos;
4691    }
4692
4693    private static boolean hasWebURI(Intent intent) {
4694        if (intent.getData() == null) {
4695            return false;
4696        }
4697        final String scheme = intent.getScheme();
4698        if (TextUtils.isEmpty(scheme)) {
4699            return false;
4700        }
4701        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4702    }
4703
4704    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4705            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4706            int userId) {
4707        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4708
4709        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4710            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4711                    candidates.size());
4712        }
4713
4714        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4715        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4716        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4717        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4719        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4720
4721        synchronized (mPackages) {
4722            final int count = candidates.size();
4723            // First, try to use linked apps. Partition the candidates into four lists:
4724            // one for the final results, one for the "do not use ever", one for "undefined status"
4725            // and finally one for "browser app type".
4726            for (int n=0; n<count; n++) {
4727                ResolveInfo info = candidates.get(n);
4728                String packageName = info.activityInfo.packageName;
4729                PackageSetting ps = mSettings.mPackages.get(packageName);
4730                if (ps != null) {
4731                    // Add to the special match all list (Browser use case)
4732                    if (info.handleAllWebDataURI) {
4733                        matchAllList.add(info);
4734                        continue;
4735                    }
4736                    // Try to get the status from User settings first
4737                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4738                    int status = (int)(packedStatus >> 32);
4739                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4740                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4741                        if (DEBUG_DOMAIN_VERIFICATION) {
4742                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4743                                    + " : linkgen=" + linkGeneration);
4744                        }
4745                        // Use link-enabled generation as preferredOrder, i.e.
4746                        // prefer newly-enabled over earlier-enabled.
4747                        info.preferredOrder = linkGeneration;
4748                        alwaysList.add(info);
4749                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4750                        if (DEBUG_DOMAIN_VERIFICATION) {
4751                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4752                        }
4753                        neverList.add(info);
4754                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4755                        if (DEBUG_DOMAIN_VERIFICATION) {
4756                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4757                        }
4758                        alwaysAskList.add(info);
4759                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4760                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4761                        if (DEBUG_DOMAIN_VERIFICATION) {
4762                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4763                        }
4764                        undefinedList.add(info);
4765                    }
4766                }
4767            }
4768
4769            // We'll want to include browser possibilities in a few cases
4770            boolean includeBrowser = false;
4771
4772            // First try to add the "always" resolution(s) for the current user, if any
4773            if (alwaysList.size() > 0) {
4774                result.addAll(alwaysList);
4775            // if there is an "always" for the parent user, add it.
4776            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4777                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4778                result.add(xpDomainInfo.resolveInfo);
4779            } else {
4780                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4781                result.addAll(undefinedList);
4782                if (xpDomainInfo != null && (
4783                        xpDomainInfo.bestDomainVerificationStatus
4784                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4785                        || xpDomainInfo.bestDomainVerificationStatus
4786                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4787                    result.add(xpDomainInfo.resolveInfo);
4788                }
4789                includeBrowser = true;
4790            }
4791
4792            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4793            // If there were 'always' entries their preferred order has been set, so we also
4794            // back that off to make the alternatives equivalent
4795            if (alwaysAskList.size() > 0) {
4796                for (ResolveInfo i : result) {
4797                    i.preferredOrder = 0;
4798                }
4799                result.addAll(alwaysAskList);
4800                includeBrowser = true;
4801            }
4802
4803            if (includeBrowser) {
4804                // Also add browsers (all of them or only the default one)
4805                if (DEBUG_DOMAIN_VERIFICATION) {
4806                    Slog.v(TAG, "   ...including browsers in candidate set");
4807                }
4808                if ((matchFlags & MATCH_ALL) != 0) {
4809                    result.addAll(matchAllList);
4810                } else {
4811                    // Browser/generic handling case.  If there's a default browser, go straight
4812                    // to that (but only if there is no other higher-priority match).
4813                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4814                    int maxMatchPrio = 0;
4815                    ResolveInfo defaultBrowserMatch = null;
4816                    final int numCandidates = matchAllList.size();
4817                    for (int n = 0; n < numCandidates; n++) {
4818                        ResolveInfo info = matchAllList.get(n);
4819                        // track the highest overall match priority...
4820                        if (info.priority > maxMatchPrio) {
4821                            maxMatchPrio = info.priority;
4822                        }
4823                        // ...and the highest-priority default browser match
4824                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4825                            if (defaultBrowserMatch == null
4826                                    || (defaultBrowserMatch.priority < info.priority)) {
4827                                if (debug) {
4828                                    Slog.v(TAG, "Considering default browser match " + info);
4829                                }
4830                                defaultBrowserMatch = info;
4831                            }
4832                        }
4833                    }
4834                    if (defaultBrowserMatch != null
4835                            && defaultBrowserMatch.priority >= maxMatchPrio
4836                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4837                    {
4838                        if (debug) {
4839                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4840                        }
4841                        result.add(defaultBrowserMatch);
4842                    } else {
4843                        result.addAll(matchAllList);
4844                    }
4845                }
4846
4847                // If there is nothing selected, add all candidates and remove the ones that the user
4848                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4849                if (result.size() == 0) {
4850                    result.addAll(candidates);
4851                    result.removeAll(neverList);
4852                }
4853            }
4854        }
4855        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4856            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4857                    result.size());
4858            for (ResolveInfo info : result) {
4859                Slog.v(TAG, "  + " + info.activityInfo);
4860            }
4861        }
4862        return result;
4863    }
4864
4865    // Returns a packed value as a long:
4866    //
4867    // high 'int'-sized word: link status: undefined/ask/never/always.
4868    // low 'int'-sized word: relative priority among 'always' results.
4869    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4870        long result = ps.getDomainVerificationStatusForUser(userId);
4871        // if none available, get the master status
4872        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4873            if (ps.getIntentFilterVerificationInfo() != null) {
4874                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4875            }
4876        }
4877        return result;
4878    }
4879
4880    private ResolveInfo querySkipCurrentProfileIntents(
4881            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4882            int flags, int sourceUserId) {
4883        if (matchingFilters != null) {
4884            int size = matchingFilters.size();
4885            for (int i = 0; i < size; i ++) {
4886                CrossProfileIntentFilter filter = matchingFilters.get(i);
4887                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4888                    // Checking if there are activities in the target user that can handle the
4889                    // intent.
4890                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4891                            flags, sourceUserId);
4892                    if (resolveInfo != null) {
4893                        return resolveInfo;
4894                    }
4895                }
4896            }
4897        }
4898        return null;
4899    }
4900
4901    // Return matching ResolveInfo if any for skip current profile intent filters.
4902    private ResolveInfo queryCrossProfileIntents(
4903            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4904            int flags, int sourceUserId) {
4905        if (matchingFilters != null) {
4906            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4907            // match the same intent. For performance reasons, it is better not to
4908            // run queryIntent twice for the same userId
4909            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4910            int size = matchingFilters.size();
4911            for (int i = 0; i < size; i++) {
4912                CrossProfileIntentFilter filter = matchingFilters.get(i);
4913                int targetUserId = filter.getTargetUserId();
4914                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4915                        && !alreadyTriedUserIds.get(targetUserId)) {
4916                    // Checking if there are activities in the target user that can handle the
4917                    // intent.
4918                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4919                            flags, sourceUserId);
4920                    if (resolveInfo != null) return resolveInfo;
4921                    alreadyTriedUserIds.put(targetUserId, true);
4922                }
4923            }
4924        }
4925        return null;
4926    }
4927
4928    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4929            String resolvedType, int flags, int sourceUserId) {
4930        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4931                resolvedType, flags, filter.getTargetUserId());
4932        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4933            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4934        }
4935        return null;
4936    }
4937
4938    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4939            int sourceUserId, int targetUserId) {
4940        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4941        String className;
4942        if (targetUserId == UserHandle.USER_OWNER) {
4943            className = FORWARD_INTENT_TO_USER_OWNER;
4944        } else {
4945            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4946        }
4947        ComponentName forwardingActivityComponentName = new ComponentName(
4948                mAndroidApplication.packageName, className);
4949        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4950                sourceUserId);
4951        if (targetUserId == UserHandle.USER_OWNER) {
4952            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4953            forwardingResolveInfo.noResourceId = true;
4954        }
4955        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4956        forwardingResolveInfo.priority = 0;
4957        forwardingResolveInfo.preferredOrder = 0;
4958        forwardingResolveInfo.match = 0;
4959        forwardingResolveInfo.isDefault = true;
4960        forwardingResolveInfo.filter = filter;
4961        forwardingResolveInfo.targetUserId = targetUserId;
4962        return forwardingResolveInfo;
4963    }
4964
4965    @Override
4966    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4967            Intent[] specifics, String[] specificTypes, Intent intent,
4968            String resolvedType, int flags, int userId) {
4969        if (!sUserManager.exists(userId)) return Collections.emptyList();
4970        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4971                false, "query intent activity options");
4972        final String resultsAction = intent.getAction();
4973
4974        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4975                | PackageManager.GET_RESOLVED_FILTER, userId);
4976
4977        if (DEBUG_INTENT_MATCHING) {
4978            Log.v(TAG, "Query " + intent + ": " + results);
4979        }
4980
4981        int specificsPos = 0;
4982        int N;
4983
4984        // todo: note that the algorithm used here is O(N^2).  This
4985        // isn't a problem in our current environment, but if we start running
4986        // into situations where we have more than 5 or 10 matches then this
4987        // should probably be changed to something smarter...
4988
4989        // First we go through and resolve each of the specific items
4990        // that were supplied, taking care of removing any corresponding
4991        // duplicate items in the generic resolve list.
4992        if (specifics != null) {
4993            for (int i=0; i<specifics.length; i++) {
4994                final Intent sintent = specifics[i];
4995                if (sintent == null) {
4996                    continue;
4997                }
4998
4999                if (DEBUG_INTENT_MATCHING) {
5000                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5001                }
5002
5003                String action = sintent.getAction();
5004                if (resultsAction != null && resultsAction.equals(action)) {
5005                    // If this action was explicitly requested, then don't
5006                    // remove things that have it.
5007                    action = null;
5008                }
5009
5010                ResolveInfo ri = null;
5011                ActivityInfo ai = null;
5012
5013                ComponentName comp = sintent.getComponent();
5014                if (comp == null) {
5015                    ri = resolveIntent(
5016                        sintent,
5017                        specificTypes != null ? specificTypes[i] : null,
5018                            flags, userId);
5019                    if (ri == null) {
5020                        continue;
5021                    }
5022                    if (ri == mResolveInfo) {
5023                        // ACK!  Must do something better with this.
5024                    }
5025                    ai = ri.activityInfo;
5026                    comp = new ComponentName(ai.applicationInfo.packageName,
5027                            ai.name);
5028                } else {
5029                    ai = getActivityInfo(comp, flags, userId);
5030                    if (ai == null) {
5031                        continue;
5032                    }
5033                }
5034
5035                // Look for any generic query activities that are duplicates
5036                // of this specific one, and remove them from the results.
5037                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5038                N = results.size();
5039                int j;
5040                for (j=specificsPos; j<N; j++) {
5041                    ResolveInfo sri = results.get(j);
5042                    if ((sri.activityInfo.name.equals(comp.getClassName())
5043                            && sri.activityInfo.applicationInfo.packageName.equals(
5044                                    comp.getPackageName()))
5045                        || (action != null && sri.filter.matchAction(action))) {
5046                        results.remove(j);
5047                        if (DEBUG_INTENT_MATCHING) Log.v(
5048                            TAG, "Removing duplicate item from " + j
5049                            + " due to specific " + specificsPos);
5050                        if (ri == null) {
5051                            ri = sri;
5052                        }
5053                        j--;
5054                        N--;
5055                    }
5056                }
5057
5058                // Add this specific item to its proper place.
5059                if (ri == null) {
5060                    ri = new ResolveInfo();
5061                    ri.activityInfo = ai;
5062                }
5063                results.add(specificsPos, ri);
5064                ri.specificIndex = i;
5065                specificsPos++;
5066            }
5067        }
5068
5069        // Now we go through the remaining generic results and remove any
5070        // duplicate actions that are found here.
5071        N = results.size();
5072        for (int i=specificsPos; i<N-1; i++) {
5073            final ResolveInfo rii = results.get(i);
5074            if (rii.filter == null) {
5075                continue;
5076            }
5077
5078            // Iterate over all of the actions of this result's intent
5079            // filter...  typically this should be just one.
5080            final Iterator<String> it = rii.filter.actionsIterator();
5081            if (it == null) {
5082                continue;
5083            }
5084            while (it.hasNext()) {
5085                final String action = it.next();
5086                if (resultsAction != null && resultsAction.equals(action)) {
5087                    // If this action was explicitly requested, then don't
5088                    // remove things that have it.
5089                    continue;
5090                }
5091                for (int j=i+1; j<N; j++) {
5092                    final ResolveInfo rij = results.get(j);
5093                    if (rij.filter != null && rij.filter.hasAction(action)) {
5094                        results.remove(j);
5095                        if (DEBUG_INTENT_MATCHING) Log.v(
5096                            TAG, "Removing duplicate item from " + j
5097                            + " due to action " + action + " at " + i);
5098                        j--;
5099                        N--;
5100                    }
5101                }
5102            }
5103
5104            // If the caller didn't request filter information, drop it now
5105            // so we don't have to marshall/unmarshall it.
5106            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5107                rii.filter = null;
5108            }
5109        }
5110
5111        // Filter out the caller activity if so requested.
5112        if (caller != null) {
5113            N = results.size();
5114            for (int i=0; i<N; i++) {
5115                ActivityInfo ainfo = results.get(i).activityInfo;
5116                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5117                        && caller.getClassName().equals(ainfo.name)) {
5118                    results.remove(i);
5119                    break;
5120                }
5121            }
5122        }
5123
5124        // If the caller didn't request filter information,
5125        // drop them now so we don't have to
5126        // marshall/unmarshall it.
5127        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5128            N = results.size();
5129            for (int i=0; i<N; i++) {
5130                results.get(i).filter = null;
5131            }
5132        }
5133
5134        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5135        return results;
5136    }
5137
5138    @Override
5139    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5140            int userId) {
5141        if (!sUserManager.exists(userId)) return Collections.emptyList();
5142        ComponentName comp = intent.getComponent();
5143        if (comp == null) {
5144            if (intent.getSelector() != null) {
5145                intent = intent.getSelector();
5146                comp = intent.getComponent();
5147            }
5148        }
5149        if (comp != null) {
5150            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5151            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5152            if (ai != null) {
5153                ResolveInfo ri = new ResolveInfo();
5154                ri.activityInfo = ai;
5155                list.add(ri);
5156            }
5157            return list;
5158        }
5159
5160        // reader
5161        synchronized (mPackages) {
5162            String pkgName = intent.getPackage();
5163            if (pkgName == null) {
5164                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5165            }
5166            final PackageParser.Package pkg = mPackages.get(pkgName);
5167            if (pkg != null) {
5168                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5169                        userId);
5170            }
5171            return null;
5172        }
5173    }
5174
5175    @Override
5176    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5177        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5178        if (!sUserManager.exists(userId)) return null;
5179        if (query != null) {
5180            if (query.size() >= 1) {
5181                // If there is more than one service with the same priority,
5182                // just arbitrarily pick the first one.
5183                return query.get(0);
5184            }
5185        }
5186        return null;
5187    }
5188
5189    @Override
5190    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5191            int userId) {
5192        if (!sUserManager.exists(userId)) return Collections.emptyList();
5193        ComponentName comp = intent.getComponent();
5194        if (comp == null) {
5195            if (intent.getSelector() != null) {
5196                intent = intent.getSelector();
5197                comp = intent.getComponent();
5198            }
5199        }
5200        if (comp != null) {
5201            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5202            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5203            if (si != null) {
5204                final ResolveInfo ri = new ResolveInfo();
5205                ri.serviceInfo = si;
5206                list.add(ri);
5207            }
5208            return list;
5209        }
5210
5211        // reader
5212        synchronized (mPackages) {
5213            String pkgName = intent.getPackage();
5214            if (pkgName == null) {
5215                return mServices.queryIntent(intent, resolvedType, flags, userId);
5216            }
5217            final PackageParser.Package pkg = mPackages.get(pkgName);
5218            if (pkg != null) {
5219                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5220                        userId);
5221            }
5222            return null;
5223        }
5224    }
5225
5226    @Override
5227    public List<ResolveInfo> queryIntentContentProviders(
5228            Intent intent, String resolvedType, int flags, int userId) {
5229        if (!sUserManager.exists(userId)) return Collections.emptyList();
5230        ComponentName comp = intent.getComponent();
5231        if (comp == null) {
5232            if (intent.getSelector() != null) {
5233                intent = intent.getSelector();
5234                comp = intent.getComponent();
5235            }
5236        }
5237        if (comp != null) {
5238            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5239            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5240            if (pi != null) {
5241                final ResolveInfo ri = new ResolveInfo();
5242                ri.providerInfo = pi;
5243                list.add(ri);
5244            }
5245            return list;
5246        }
5247
5248        // reader
5249        synchronized (mPackages) {
5250            String pkgName = intent.getPackage();
5251            if (pkgName == null) {
5252                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5253            }
5254            final PackageParser.Package pkg = mPackages.get(pkgName);
5255            if (pkg != null) {
5256                return mProviders.queryIntentForPackage(
5257                        intent, resolvedType, flags, pkg.providers, userId);
5258            }
5259            return null;
5260        }
5261    }
5262
5263    @Override
5264    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5265        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5266
5267        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5268
5269        // writer
5270        synchronized (mPackages) {
5271            ArrayList<PackageInfo> list;
5272            if (listUninstalled) {
5273                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5274                for (PackageSetting ps : mSettings.mPackages.values()) {
5275                    PackageInfo pi;
5276                    if (ps.pkg != null) {
5277                        pi = generatePackageInfo(ps.pkg, flags, userId);
5278                    } else {
5279                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5280                    }
5281                    if (pi != null) {
5282                        list.add(pi);
5283                    }
5284                }
5285            } else {
5286                list = new ArrayList<PackageInfo>(mPackages.size());
5287                for (PackageParser.Package p : mPackages.values()) {
5288                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5289                    if (pi != null) {
5290                        list.add(pi);
5291                    }
5292                }
5293            }
5294
5295            return new ParceledListSlice<PackageInfo>(list);
5296        }
5297    }
5298
5299    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5300            String[] permissions, boolean[] tmp, int flags, int userId) {
5301        int numMatch = 0;
5302        final PermissionsState permissionsState = ps.getPermissionsState();
5303        for (int i=0; i<permissions.length; i++) {
5304            final String permission = permissions[i];
5305            if (permissionsState.hasPermission(permission, userId)) {
5306                tmp[i] = true;
5307                numMatch++;
5308            } else {
5309                tmp[i] = false;
5310            }
5311        }
5312        if (numMatch == 0) {
5313            return;
5314        }
5315        PackageInfo pi;
5316        if (ps.pkg != null) {
5317            pi = generatePackageInfo(ps.pkg, flags, userId);
5318        } else {
5319            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5320        }
5321        // The above might return null in cases of uninstalled apps or install-state
5322        // skew across users/profiles.
5323        if (pi != null) {
5324            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5325                if (numMatch == permissions.length) {
5326                    pi.requestedPermissions = permissions;
5327                } else {
5328                    pi.requestedPermissions = new String[numMatch];
5329                    numMatch = 0;
5330                    for (int i=0; i<permissions.length; i++) {
5331                        if (tmp[i]) {
5332                            pi.requestedPermissions[numMatch] = permissions[i];
5333                            numMatch++;
5334                        }
5335                    }
5336                }
5337            }
5338            list.add(pi);
5339        }
5340    }
5341
5342    @Override
5343    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5344            String[] permissions, int flags, int userId) {
5345        if (!sUserManager.exists(userId)) return null;
5346        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5347
5348        // writer
5349        synchronized (mPackages) {
5350            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5351            boolean[] tmpBools = new boolean[permissions.length];
5352            if (listUninstalled) {
5353                for (PackageSetting ps : mSettings.mPackages.values()) {
5354                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5355                }
5356            } else {
5357                for (PackageParser.Package pkg : mPackages.values()) {
5358                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5359                    if (ps != null) {
5360                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5361                                userId);
5362                    }
5363                }
5364            }
5365
5366            return new ParceledListSlice<PackageInfo>(list);
5367        }
5368    }
5369
5370    @Override
5371    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5372        if (!sUserManager.exists(userId)) return null;
5373        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5374
5375        // writer
5376        synchronized (mPackages) {
5377            ArrayList<ApplicationInfo> list;
5378            if (listUninstalled) {
5379                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5380                for (PackageSetting ps : mSettings.mPackages.values()) {
5381                    ApplicationInfo ai;
5382                    if (ps.pkg != null) {
5383                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5384                                ps.readUserState(userId), userId);
5385                    } else {
5386                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5387                    }
5388                    if (ai != null) {
5389                        list.add(ai);
5390                    }
5391                }
5392            } else {
5393                list = new ArrayList<ApplicationInfo>(mPackages.size());
5394                for (PackageParser.Package p : mPackages.values()) {
5395                    if (p.mExtras != null) {
5396                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5397                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5398                        if (ai != null) {
5399                            list.add(ai);
5400                        }
5401                    }
5402                }
5403            }
5404
5405            return new ParceledListSlice<ApplicationInfo>(list);
5406        }
5407    }
5408
5409    public List<ApplicationInfo> getPersistentApplications(int flags) {
5410        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5411
5412        // reader
5413        synchronized (mPackages) {
5414            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5415            final int userId = UserHandle.getCallingUserId();
5416            while (i.hasNext()) {
5417                final PackageParser.Package p = i.next();
5418                if (p.applicationInfo != null
5419                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5420                        && (!mSafeMode || isSystemApp(p))) {
5421                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5422                    if (ps != null) {
5423                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5424                                ps.readUserState(userId), userId);
5425                        if (ai != null) {
5426                            finalList.add(ai);
5427                        }
5428                    }
5429                }
5430            }
5431        }
5432
5433        return finalList;
5434    }
5435
5436    @Override
5437    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5438        if (!sUserManager.exists(userId)) return null;
5439        // reader
5440        synchronized (mPackages) {
5441            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5442            PackageSetting ps = provider != null
5443                    ? mSettings.mPackages.get(provider.owner.packageName)
5444                    : null;
5445            return ps != null
5446                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5447                    && (!mSafeMode || (provider.info.applicationInfo.flags
5448                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5449                    ? PackageParser.generateProviderInfo(provider, flags,
5450                            ps.readUserState(userId), userId)
5451                    : null;
5452        }
5453    }
5454
5455    /**
5456     * @deprecated
5457     */
5458    @Deprecated
5459    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5460        // reader
5461        synchronized (mPackages) {
5462            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5463                    .entrySet().iterator();
5464            final int userId = UserHandle.getCallingUserId();
5465            while (i.hasNext()) {
5466                Map.Entry<String, PackageParser.Provider> entry = i.next();
5467                PackageParser.Provider p = entry.getValue();
5468                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5469
5470                if (ps != null && p.syncable
5471                        && (!mSafeMode || (p.info.applicationInfo.flags
5472                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5473                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5474                            ps.readUserState(userId), userId);
5475                    if (info != null) {
5476                        outNames.add(entry.getKey());
5477                        outInfo.add(info);
5478                    }
5479                }
5480            }
5481        }
5482    }
5483
5484    @Override
5485    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5486            int uid, int flags) {
5487        ArrayList<ProviderInfo> finalList = null;
5488        // reader
5489        synchronized (mPackages) {
5490            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5491            final int userId = processName != null ?
5492                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5493            while (i.hasNext()) {
5494                final PackageParser.Provider p = i.next();
5495                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5496                if (ps != null && p.info.authority != null
5497                        && (processName == null
5498                                || (p.info.processName.equals(processName)
5499                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5500                        && mSettings.isEnabledLPr(p.info, flags, userId)
5501                        && (!mSafeMode
5502                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5503                    if (finalList == null) {
5504                        finalList = new ArrayList<ProviderInfo>(3);
5505                    }
5506                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5507                            ps.readUserState(userId), userId);
5508                    if (info != null) {
5509                        finalList.add(info);
5510                    }
5511                }
5512            }
5513        }
5514
5515        if (finalList != null) {
5516            Collections.sort(finalList, mProviderInitOrderSorter);
5517            return new ParceledListSlice<ProviderInfo>(finalList);
5518        }
5519
5520        return null;
5521    }
5522
5523    @Override
5524    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5525            int flags) {
5526        // reader
5527        synchronized (mPackages) {
5528            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5529            return PackageParser.generateInstrumentationInfo(i, flags);
5530        }
5531    }
5532
5533    @Override
5534    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5535            int flags) {
5536        ArrayList<InstrumentationInfo> finalList =
5537            new ArrayList<InstrumentationInfo>();
5538
5539        // reader
5540        synchronized (mPackages) {
5541            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5542            while (i.hasNext()) {
5543                final PackageParser.Instrumentation p = i.next();
5544                if (targetPackage == null
5545                        || targetPackage.equals(p.info.targetPackage)) {
5546                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5547                            flags);
5548                    if (ii != null) {
5549                        finalList.add(ii);
5550                    }
5551                }
5552            }
5553        }
5554
5555        return finalList;
5556    }
5557
5558    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5559        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5560        if (overlays == null) {
5561            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5562            return;
5563        }
5564        for (PackageParser.Package opkg : overlays.values()) {
5565            // Not much to do if idmap fails: we already logged the error
5566            // and we certainly don't want to abort installation of pkg simply
5567            // because an overlay didn't fit properly. For these reasons,
5568            // ignore the return value of createIdmapForPackagePairLI.
5569            createIdmapForPackagePairLI(pkg, opkg);
5570        }
5571    }
5572
5573    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5574            PackageParser.Package opkg) {
5575        if (!opkg.mTrustedOverlay) {
5576            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5577                    opkg.baseCodePath + ": overlay not trusted");
5578            return false;
5579        }
5580        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5581        if (overlaySet == null) {
5582            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5583                    opkg.baseCodePath + " but target package has no known overlays");
5584            return false;
5585        }
5586        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5587        // TODO: generate idmap for split APKs
5588        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5589            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5590                    + opkg.baseCodePath);
5591            return false;
5592        }
5593        PackageParser.Package[] overlayArray =
5594            overlaySet.values().toArray(new PackageParser.Package[0]);
5595        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5596            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5597                return p1.mOverlayPriority - p2.mOverlayPriority;
5598            }
5599        };
5600        Arrays.sort(overlayArray, cmp);
5601
5602        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5603        int i = 0;
5604        for (PackageParser.Package p : overlayArray) {
5605            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5606        }
5607        return true;
5608    }
5609
5610    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5611        final File[] files = dir.listFiles();
5612        if (ArrayUtils.isEmpty(files)) {
5613            Log.d(TAG, "No files in app dir " + dir);
5614            return;
5615        }
5616
5617        if (DEBUG_PACKAGE_SCANNING) {
5618            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5619                    + " flags=0x" + Integer.toHexString(parseFlags));
5620        }
5621
5622        for (File file : files) {
5623            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5624                    && !PackageInstallerService.isStageName(file.getName());
5625            if (!isPackage) {
5626                // Ignore entries which are not packages
5627                continue;
5628            }
5629            try {
5630                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5631                        scanFlags, currentTime, null);
5632            } catch (PackageManagerException e) {
5633                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5634
5635                // Delete invalid userdata apps
5636                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5637                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5638                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5639                    if (file.isDirectory()) {
5640                        mInstaller.rmPackageDir(file.getAbsolutePath());
5641                    } else {
5642                        file.delete();
5643                    }
5644                }
5645            }
5646        }
5647    }
5648
5649    private static File getSettingsProblemFile() {
5650        File dataDir = Environment.getDataDirectory();
5651        File systemDir = new File(dataDir, "system");
5652        File fname = new File(systemDir, "uiderrors.txt");
5653        return fname;
5654    }
5655
5656    static void reportSettingsProblem(int priority, String msg) {
5657        logCriticalInfo(priority, msg);
5658    }
5659
5660    static void logCriticalInfo(int priority, String msg) {
5661        Slog.println(priority, TAG, msg);
5662        EventLogTags.writePmCriticalInfo(msg);
5663        try {
5664            File fname = getSettingsProblemFile();
5665            FileOutputStream out = new FileOutputStream(fname, true);
5666            PrintWriter pw = new FastPrintWriter(out);
5667            SimpleDateFormat formatter = new SimpleDateFormat();
5668            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5669            pw.println(dateString + ": " + msg);
5670            pw.close();
5671            FileUtils.setPermissions(
5672                    fname.toString(),
5673                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5674                    -1, -1);
5675        } catch (java.io.IOException e) {
5676        }
5677    }
5678
5679    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5680            PackageParser.Package pkg, File srcFile, int parseFlags)
5681            throws PackageManagerException {
5682        if (ps != null
5683                && ps.codePath.equals(srcFile)
5684                && ps.timeStamp == srcFile.lastModified()
5685                && !isCompatSignatureUpdateNeeded(pkg)
5686                && !isRecoverSignatureUpdateNeeded(pkg)) {
5687            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5688            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5689            ArraySet<PublicKey> signingKs;
5690            synchronized (mPackages) {
5691                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5692            }
5693            if (ps.signatures.mSignatures != null
5694                    && ps.signatures.mSignatures.length != 0
5695                    && signingKs != null) {
5696                // Optimization: reuse the existing cached certificates
5697                // if the package appears to be unchanged.
5698                pkg.mSignatures = ps.signatures.mSignatures;
5699                pkg.mSigningKeys = signingKs;
5700                return;
5701            }
5702
5703            Slog.w(TAG, "PackageSetting for " + ps.name
5704                    + " is missing signatures.  Collecting certs again to recover them.");
5705        } else {
5706            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5707        }
5708
5709        try {
5710            pp.collectCertificates(pkg, parseFlags);
5711            pp.collectManifestDigest(pkg);
5712        } catch (PackageParserException e) {
5713            throw PackageManagerException.from(e);
5714        }
5715    }
5716
5717    /*
5718     *  Scan a package and return the newly parsed package.
5719     *  Returns null in case of errors and the error code is stored in mLastScanError
5720     */
5721    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5722            long currentTime, UserHandle user) throws PackageManagerException {
5723        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5724        parseFlags |= mDefParseFlags;
5725        PackageParser pp = new PackageParser();
5726        pp.setSeparateProcesses(mSeparateProcesses);
5727        pp.setOnlyCoreApps(mOnlyCore);
5728        pp.setDisplayMetrics(mMetrics);
5729
5730        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5731            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5732        }
5733
5734        final PackageParser.Package pkg;
5735        try {
5736            pkg = pp.parsePackage(scanFile, parseFlags);
5737        } catch (PackageParserException e) {
5738            throw PackageManagerException.from(e);
5739        }
5740
5741        PackageSetting ps = null;
5742        PackageSetting updatedPkg;
5743        // reader
5744        synchronized (mPackages) {
5745            // Look to see if we already know about this package.
5746            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5747            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5748                // This package has been renamed to its original name.  Let's
5749                // use that.
5750                ps = mSettings.peekPackageLPr(oldName);
5751            }
5752            // If there was no original package, see one for the real package name.
5753            if (ps == null) {
5754                ps = mSettings.peekPackageLPr(pkg.packageName);
5755            }
5756            // Check to see if this package could be hiding/updating a system
5757            // package.  Must look for it either under the original or real
5758            // package name depending on our state.
5759            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5760            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5761        }
5762        boolean updatedPkgBetter = false;
5763        // First check if this is a system package that may involve an update
5764        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5765            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5766            // it needs to drop FLAG_PRIVILEGED.
5767            if (locationIsPrivileged(scanFile)) {
5768                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5769            } else {
5770                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5771            }
5772
5773            if (ps != null && !ps.codePath.equals(scanFile)) {
5774                // The path has changed from what was last scanned...  check the
5775                // version of the new path against what we have stored to determine
5776                // what to do.
5777                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5778                if (pkg.mVersionCode <= ps.versionCode) {
5779                    // The system package has been updated and the code path does not match
5780                    // Ignore entry. Skip it.
5781                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5782                            + " ignored: updated version " + ps.versionCode
5783                            + " better than this " + pkg.mVersionCode);
5784                    if (!updatedPkg.codePath.equals(scanFile)) {
5785                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5786                                + ps.name + " changing from " + updatedPkg.codePathString
5787                                + " to " + scanFile);
5788                        updatedPkg.codePath = scanFile;
5789                        updatedPkg.codePathString = scanFile.toString();
5790                        updatedPkg.resourcePath = scanFile;
5791                        updatedPkg.resourcePathString = scanFile.toString();
5792                    }
5793                    updatedPkg.pkg = pkg;
5794                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5795                            "Package " + ps.name + " at " + scanFile
5796                                    + " ignored: updated version " + ps.versionCode
5797                                    + " better than this " + pkg.mVersionCode);
5798                } else {
5799                    // The current app on the system partition is better than
5800                    // what we have updated to on the data partition; switch
5801                    // back to the system partition version.
5802                    // At this point, its safely assumed that package installation for
5803                    // apps in system partition will go through. If not there won't be a working
5804                    // version of the app
5805                    // writer
5806                    synchronized (mPackages) {
5807                        // Just remove the loaded entries from package lists.
5808                        mPackages.remove(ps.name);
5809                    }
5810
5811                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5812                            + " reverting from " + ps.codePathString
5813                            + ": new version " + pkg.mVersionCode
5814                            + " better than installed " + ps.versionCode);
5815
5816                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5817                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5818                    synchronized (mInstallLock) {
5819                        args.cleanUpResourcesLI();
5820                    }
5821                    synchronized (mPackages) {
5822                        mSettings.enableSystemPackageLPw(ps.name);
5823                    }
5824                    updatedPkgBetter = true;
5825                }
5826            }
5827        }
5828
5829        if (updatedPkg != null) {
5830            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5831            // initially
5832            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5833
5834            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5835            // flag set initially
5836            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5837                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5838            }
5839        }
5840
5841        // Verify certificates against what was last scanned
5842        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5843
5844        /*
5845         * A new system app appeared, but we already had a non-system one of the
5846         * same name installed earlier.
5847         */
5848        boolean shouldHideSystemApp = false;
5849        if (updatedPkg == null && ps != null
5850                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5851            /*
5852             * Check to make sure the signatures match first. If they don't,
5853             * wipe the installed application and its data.
5854             */
5855            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5856                    != PackageManager.SIGNATURE_MATCH) {
5857                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5858                        + " signatures don't match existing userdata copy; removing");
5859                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5860                ps = null;
5861            } else {
5862                /*
5863                 * If the newly-added system app is an older version than the
5864                 * already installed version, hide it. It will be scanned later
5865                 * and re-added like an update.
5866                 */
5867                if (pkg.mVersionCode <= ps.versionCode) {
5868                    shouldHideSystemApp = true;
5869                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5870                            + " but new version " + pkg.mVersionCode + " better than installed "
5871                            + ps.versionCode + "; hiding system");
5872                } else {
5873                    /*
5874                     * The newly found system app is a newer version that the
5875                     * one previously installed. Simply remove the
5876                     * already-installed application and replace it with our own
5877                     * while keeping the application data.
5878                     */
5879                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5880                            + " reverting from " + ps.codePathString + ": new version "
5881                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5882                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5883                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5884                    synchronized (mInstallLock) {
5885                        args.cleanUpResourcesLI();
5886                    }
5887                }
5888            }
5889        }
5890
5891        // The apk is forward locked (not public) if its code and resources
5892        // are kept in different files. (except for app in either system or
5893        // vendor path).
5894        // TODO grab this value from PackageSettings
5895        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5896            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5897                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5898            }
5899        }
5900
5901        // TODO: extend to support forward-locked splits
5902        String resourcePath = null;
5903        String baseResourcePath = null;
5904        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5905            if (ps != null && ps.resourcePathString != null) {
5906                resourcePath = ps.resourcePathString;
5907                baseResourcePath = ps.resourcePathString;
5908            } else {
5909                // Should not happen at all. Just log an error.
5910                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5911            }
5912        } else {
5913            resourcePath = pkg.codePath;
5914            baseResourcePath = pkg.baseCodePath;
5915        }
5916
5917        // Set application objects path explicitly.
5918        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5919        pkg.applicationInfo.setCodePath(pkg.codePath);
5920        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5921        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5922        pkg.applicationInfo.setResourcePath(resourcePath);
5923        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5924        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5925
5926        // Note that we invoke the following method only if we are about to unpack an application
5927        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5928                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5929
5930        /*
5931         * If the system app should be overridden by a previously installed
5932         * data, hide the system app now and let the /data/app scan pick it up
5933         * again.
5934         */
5935        if (shouldHideSystemApp) {
5936            synchronized (mPackages) {
5937                mSettings.disableSystemPackageLPw(pkg.packageName);
5938            }
5939        }
5940
5941        return scannedPkg;
5942    }
5943
5944    private static String fixProcessName(String defProcessName,
5945            String processName, int uid) {
5946        if (processName == null) {
5947            return defProcessName;
5948        }
5949        return processName;
5950    }
5951
5952    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5953            throws PackageManagerException {
5954        if (pkgSetting.signatures.mSignatures != null) {
5955            // Already existing package. Make sure signatures match
5956            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5957                    == PackageManager.SIGNATURE_MATCH;
5958            if (!match) {
5959                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5960                        == PackageManager.SIGNATURE_MATCH;
5961            }
5962            if (!match) {
5963                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5964                        == PackageManager.SIGNATURE_MATCH;
5965            }
5966            if (!match) {
5967                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5968                        + pkg.packageName + " signatures do not match the "
5969                        + "previously installed version; ignoring!");
5970            }
5971        }
5972
5973        // Check for shared user signatures
5974        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5975            // Already existing package. Make sure signatures match
5976            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5977                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5978            if (!match) {
5979                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5980                        == PackageManager.SIGNATURE_MATCH;
5981            }
5982            if (!match) {
5983                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5984                        == PackageManager.SIGNATURE_MATCH;
5985            }
5986            if (!match) {
5987                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5988                        "Package " + pkg.packageName
5989                        + " has no signatures that match those in shared user "
5990                        + pkgSetting.sharedUser.name + "; ignoring!");
5991            }
5992        }
5993    }
5994
5995    /**
5996     * Enforces that only the system UID or root's UID can call a method exposed
5997     * via Binder.
5998     *
5999     * @param message used as message if SecurityException is thrown
6000     * @throws SecurityException if the caller is not system or root
6001     */
6002    private static final void enforceSystemOrRoot(String message) {
6003        final int uid = Binder.getCallingUid();
6004        if (uid != Process.SYSTEM_UID && uid != 0) {
6005            throw new SecurityException(message);
6006        }
6007    }
6008
6009    @Override
6010    public void performBootDexOpt() {
6011        enforceSystemOrRoot("Only the system can request dexopt be performed");
6012
6013        // Before everything else, see whether we need to fstrim.
6014        try {
6015            IMountService ms = PackageHelper.getMountService();
6016            if (ms != null) {
6017                final boolean isUpgrade = isUpgrade();
6018                boolean doTrim = isUpgrade;
6019                if (doTrim) {
6020                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6021                } else {
6022                    final long interval = android.provider.Settings.Global.getLong(
6023                            mContext.getContentResolver(),
6024                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6025                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6026                    if (interval > 0) {
6027                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6028                        if (timeSinceLast > interval) {
6029                            doTrim = true;
6030                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6031                                    + "; running immediately");
6032                        }
6033                    }
6034                }
6035                if (doTrim) {
6036                    if (!isFirstBoot()) {
6037                        try {
6038                            ActivityManagerNative.getDefault().showBootMessage(
6039                                    mContext.getResources().getString(
6040                                            R.string.android_upgrading_fstrim), true);
6041                        } catch (RemoteException e) {
6042                        }
6043                    }
6044                    ms.runMaintenance();
6045                }
6046            } else {
6047                Slog.e(TAG, "Mount service unavailable!");
6048            }
6049        } catch (RemoteException e) {
6050            // Can't happen; MountService is local
6051        }
6052
6053        final ArraySet<PackageParser.Package> pkgs;
6054        synchronized (mPackages) {
6055            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6056        }
6057
6058        if (pkgs != null) {
6059            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6060            // in case the device runs out of space.
6061            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6062            // Give priority to core apps.
6063            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6064                PackageParser.Package pkg = it.next();
6065                if (pkg.coreApp) {
6066                    if (DEBUG_DEXOPT) {
6067                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6068                    }
6069                    sortedPkgs.add(pkg);
6070                    it.remove();
6071                }
6072            }
6073            // Give priority to system apps that listen for pre boot complete.
6074            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6075            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6076            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6077                PackageParser.Package pkg = it.next();
6078                if (pkgNames.contains(pkg.packageName)) {
6079                    if (DEBUG_DEXOPT) {
6080                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6081                    }
6082                    sortedPkgs.add(pkg);
6083                    it.remove();
6084                }
6085            }
6086            // Give priority to system apps.
6087            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6088                PackageParser.Package pkg = it.next();
6089                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6090                    if (DEBUG_DEXOPT) {
6091                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6092                    }
6093                    sortedPkgs.add(pkg);
6094                    it.remove();
6095                }
6096            }
6097            // Give priority to updated system apps.
6098            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6099                PackageParser.Package pkg = it.next();
6100                if (pkg.isUpdatedSystemApp()) {
6101                    if (DEBUG_DEXOPT) {
6102                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6103                    }
6104                    sortedPkgs.add(pkg);
6105                    it.remove();
6106                }
6107            }
6108            // Give priority to apps that listen for boot complete.
6109            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6110            pkgNames = getPackageNamesForIntent(intent);
6111            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6112                PackageParser.Package pkg = it.next();
6113                if (pkgNames.contains(pkg.packageName)) {
6114                    if (DEBUG_DEXOPT) {
6115                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6116                    }
6117                    sortedPkgs.add(pkg);
6118                    it.remove();
6119                }
6120            }
6121            // Filter out packages that aren't recently used.
6122            filterRecentlyUsedApps(pkgs);
6123            // Add all remaining apps.
6124            for (PackageParser.Package pkg : pkgs) {
6125                if (DEBUG_DEXOPT) {
6126                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6127                }
6128                sortedPkgs.add(pkg);
6129            }
6130
6131            // If we want to be lazy, filter everything that wasn't recently used.
6132            if (mLazyDexOpt) {
6133                filterRecentlyUsedApps(sortedPkgs);
6134            }
6135
6136            int i = 0;
6137            int total = sortedPkgs.size();
6138            File dataDir = Environment.getDataDirectory();
6139            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6140            if (lowThreshold == 0) {
6141                throw new IllegalStateException("Invalid low memory threshold");
6142            }
6143            for (PackageParser.Package pkg : sortedPkgs) {
6144                long usableSpace = dataDir.getUsableSpace();
6145                if (usableSpace < lowThreshold) {
6146                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6147                    break;
6148                }
6149                performBootDexOpt(pkg, ++i, total);
6150            }
6151        }
6152    }
6153
6154    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6155        // Filter out packages that aren't recently used.
6156        //
6157        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6158        // should do a full dexopt.
6159        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6160            int total = pkgs.size();
6161            int skipped = 0;
6162            long now = System.currentTimeMillis();
6163            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6164                PackageParser.Package pkg = i.next();
6165                long then = pkg.mLastPackageUsageTimeInMills;
6166                if (then + mDexOptLRUThresholdInMills < now) {
6167                    if (DEBUG_DEXOPT) {
6168                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6169                              ((then == 0) ? "never" : new Date(then)));
6170                    }
6171                    i.remove();
6172                    skipped++;
6173                }
6174            }
6175            if (DEBUG_DEXOPT) {
6176                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6177            }
6178        }
6179    }
6180
6181    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6182        List<ResolveInfo> ris = null;
6183        try {
6184            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6185                    intent, null, 0, UserHandle.USER_OWNER);
6186        } catch (RemoteException e) {
6187        }
6188        ArraySet<String> pkgNames = new ArraySet<String>();
6189        if (ris != null) {
6190            for (ResolveInfo ri : ris) {
6191                pkgNames.add(ri.activityInfo.packageName);
6192            }
6193        }
6194        return pkgNames;
6195    }
6196
6197    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6198        if (DEBUG_DEXOPT) {
6199            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6200        }
6201        if (!isFirstBoot()) {
6202            try {
6203                ActivityManagerNative.getDefault().showBootMessage(
6204                        mContext.getResources().getString(R.string.android_upgrading_apk,
6205                                curr, total), true);
6206            } catch (RemoteException e) {
6207            }
6208        }
6209        PackageParser.Package p = pkg;
6210        synchronized (mInstallLock) {
6211            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6212                    false /* force dex */, false /* defer */, true /* include dependencies */,
6213                    false /* boot complete */);
6214        }
6215    }
6216
6217    @Override
6218    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6219        return performDexOpt(packageName, instructionSet, false);
6220    }
6221
6222    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6223        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6224        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6225        if (!dexopt && !updateUsage) {
6226            // We aren't going to dexopt or update usage, so bail early.
6227            return false;
6228        }
6229        PackageParser.Package p;
6230        final String targetInstructionSet;
6231        synchronized (mPackages) {
6232            p = mPackages.get(packageName);
6233            if (p == null) {
6234                return false;
6235            }
6236            if (updateUsage) {
6237                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6238            }
6239            mPackageUsage.write(false);
6240            if (!dexopt) {
6241                // We aren't going to dexopt, so bail early.
6242                return false;
6243            }
6244
6245            targetInstructionSet = instructionSet != null ? instructionSet :
6246                    getPrimaryInstructionSet(p.applicationInfo);
6247            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6248                return false;
6249            }
6250        }
6251        long callingId = Binder.clearCallingIdentity();
6252        try {
6253            synchronized (mInstallLock) {
6254                final String[] instructionSets = new String[] { targetInstructionSet };
6255                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6256                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6257                        true /* boot complete */);
6258                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6259            }
6260        } finally {
6261            Binder.restoreCallingIdentity(callingId);
6262        }
6263    }
6264
6265    public ArraySet<String> getPackagesThatNeedDexOpt() {
6266        ArraySet<String> pkgs = null;
6267        synchronized (mPackages) {
6268            for (PackageParser.Package p : mPackages.values()) {
6269                if (DEBUG_DEXOPT) {
6270                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6271                }
6272                if (!p.mDexOptPerformed.isEmpty()) {
6273                    continue;
6274                }
6275                if (pkgs == null) {
6276                    pkgs = new ArraySet<String>();
6277                }
6278                pkgs.add(p.packageName);
6279            }
6280        }
6281        return pkgs;
6282    }
6283
6284    public void shutdown() {
6285        mPackageUsage.write(true);
6286    }
6287
6288    @Override
6289    public void forceDexOpt(String packageName) {
6290        enforceSystemOrRoot("forceDexOpt");
6291
6292        PackageParser.Package pkg;
6293        synchronized (mPackages) {
6294            pkg = mPackages.get(packageName);
6295            if (pkg == null) {
6296                throw new IllegalArgumentException("Missing package: " + packageName);
6297            }
6298        }
6299
6300        synchronized (mInstallLock) {
6301            final String[] instructionSets = new String[] {
6302                    getPrimaryInstructionSet(pkg.applicationInfo) };
6303            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6304                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6305                    true /* boot complete */);
6306            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6307                throw new IllegalStateException("Failed to dexopt: " + res);
6308            }
6309        }
6310    }
6311
6312    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6313        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6314            Slog.w(TAG, "Unable to update from " + oldPkg.name
6315                    + " to " + newPkg.packageName
6316                    + ": old package not in system partition");
6317            return false;
6318        } else if (mPackages.get(oldPkg.name) != null) {
6319            Slog.w(TAG, "Unable to update from " + oldPkg.name
6320                    + " to " + newPkg.packageName
6321                    + ": old package still exists");
6322            return false;
6323        }
6324        return true;
6325    }
6326
6327    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6328        int[] users = sUserManager.getUserIds();
6329        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6330        if (res < 0) {
6331            return res;
6332        }
6333        for (int user : users) {
6334            if (user != 0) {
6335                res = mInstaller.createUserData(volumeUuid, packageName,
6336                        UserHandle.getUid(user, uid), user, seinfo);
6337                if (res < 0) {
6338                    return res;
6339                }
6340            }
6341        }
6342        return res;
6343    }
6344
6345    private int removeDataDirsLI(String volumeUuid, String packageName) {
6346        int[] users = sUserManager.getUserIds();
6347        int res = 0;
6348        for (int user : users) {
6349            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6350            if (resInner < 0) {
6351                res = resInner;
6352            }
6353        }
6354
6355        return res;
6356    }
6357
6358    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6359        int[] users = sUserManager.getUserIds();
6360        int res = 0;
6361        for (int user : users) {
6362            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6363            if (resInner < 0) {
6364                res = resInner;
6365            }
6366        }
6367        return res;
6368    }
6369
6370    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6371            PackageParser.Package changingLib) {
6372        if (file.path != null) {
6373            usesLibraryFiles.add(file.path);
6374            return;
6375        }
6376        PackageParser.Package p = mPackages.get(file.apk);
6377        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6378            // If we are doing this while in the middle of updating a library apk,
6379            // then we need to make sure to use that new apk for determining the
6380            // dependencies here.  (We haven't yet finished committing the new apk
6381            // to the package manager state.)
6382            if (p == null || p.packageName.equals(changingLib.packageName)) {
6383                p = changingLib;
6384            }
6385        }
6386        if (p != null) {
6387            usesLibraryFiles.addAll(p.getAllCodePaths());
6388        }
6389    }
6390
6391    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6392            PackageParser.Package changingLib) throws PackageManagerException {
6393        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6394            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6395            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6396            for (int i=0; i<N; i++) {
6397                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6398                if (file == null) {
6399                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6400                            "Package " + pkg.packageName + " requires unavailable shared library "
6401                            + pkg.usesLibraries.get(i) + "; failing!");
6402                }
6403                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6404            }
6405            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6406            for (int i=0; i<N; i++) {
6407                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6408                if (file == null) {
6409                    Slog.w(TAG, "Package " + pkg.packageName
6410                            + " desires unavailable shared library "
6411                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6412                } else {
6413                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6414                }
6415            }
6416            N = usesLibraryFiles.size();
6417            if (N > 0) {
6418                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6419            } else {
6420                pkg.usesLibraryFiles = null;
6421            }
6422        }
6423    }
6424
6425    private static boolean hasString(List<String> list, List<String> which) {
6426        if (list == null) {
6427            return false;
6428        }
6429        for (int i=list.size()-1; i>=0; i--) {
6430            for (int j=which.size()-1; j>=0; j--) {
6431                if (which.get(j).equals(list.get(i))) {
6432                    return true;
6433                }
6434            }
6435        }
6436        return false;
6437    }
6438
6439    private void updateAllSharedLibrariesLPw() {
6440        for (PackageParser.Package pkg : mPackages.values()) {
6441            try {
6442                updateSharedLibrariesLPw(pkg, null);
6443            } catch (PackageManagerException e) {
6444                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6445            }
6446        }
6447    }
6448
6449    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6450            PackageParser.Package changingPkg) {
6451        ArrayList<PackageParser.Package> res = null;
6452        for (PackageParser.Package pkg : mPackages.values()) {
6453            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6454                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6455                if (res == null) {
6456                    res = new ArrayList<PackageParser.Package>();
6457                }
6458                res.add(pkg);
6459                try {
6460                    updateSharedLibrariesLPw(pkg, changingPkg);
6461                } catch (PackageManagerException e) {
6462                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6463                }
6464            }
6465        }
6466        return res;
6467    }
6468
6469    /**
6470     * Derive the value of the {@code cpuAbiOverride} based on the provided
6471     * value and an optional stored value from the package settings.
6472     */
6473    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6474        String cpuAbiOverride = null;
6475
6476        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6477            cpuAbiOverride = null;
6478        } else if (abiOverride != null) {
6479            cpuAbiOverride = abiOverride;
6480        } else if (settings != null) {
6481            cpuAbiOverride = settings.cpuAbiOverrideString;
6482        }
6483
6484        return cpuAbiOverride;
6485    }
6486
6487    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6488            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6489        boolean success = false;
6490        try {
6491            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6492                    currentTime, user);
6493            success = true;
6494            return res;
6495        } finally {
6496            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6497                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6498            }
6499        }
6500    }
6501
6502    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6503            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6504        final File scanFile = new File(pkg.codePath);
6505        if (pkg.applicationInfo.getCodePath() == null ||
6506                pkg.applicationInfo.getResourcePath() == null) {
6507            // Bail out. The resource and code paths haven't been set.
6508            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6509                    "Code and resource paths haven't been set correctly");
6510        }
6511
6512        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6513            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6514        } else {
6515            // Only allow system apps to be flagged as core apps.
6516            pkg.coreApp = false;
6517        }
6518
6519        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6520            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6521        }
6522
6523        if (mCustomResolverComponentName != null &&
6524                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6525            setUpCustomResolverActivity(pkg);
6526        }
6527
6528        if (pkg.packageName.equals("android")) {
6529            synchronized (mPackages) {
6530                if (mAndroidApplication != null) {
6531                    Slog.w(TAG, "*************************************************");
6532                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6533                    Slog.w(TAG, " file=" + scanFile);
6534                    Slog.w(TAG, "*************************************************");
6535                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6536                            "Core android package being redefined.  Skipping.");
6537                }
6538
6539                // Set up information for our fall-back user intent resolution activity.
6540                mPlatformPackage = pkg;
6541                pkg.mVersionCode = mSdkVersion;
6542                mAndroidApplication = pkg.applicationInfo;
6543
6544                if (!mResolverReplaced) {
6545                    mResolveActivity.applicationInfo = mAndroidApplication;
6546                    mResolveActivity.name = ResolverActivity.class.getName();
6547                    mResolveActivity.packageName = mAndroidApplication.packageName;
6548                    mResolveActivity.processName = "system:ui";
6549                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6550                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6551                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6552                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6553                    mResolveActivity.exported = true;
6554                    mResolveActivity.enabled = true;
6555                    mResolveInfo.activityInfo = mResolveActivity;
6556                    mResolveInfo.priority = 0;
6557                    mResolveInfo.preferredOrder = 0;
6558                    mResolveInfo.match = 0;
6559                    mResolveComponentName = new ComponentName(
6560                            mAndroidApplication.packageName, mResolveActivity.name);
6561                }
6562            }
6563        }
6564
6565        if (DEBUG_PACKAGE_SCANNING) {
6566            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6567                Log.d(TAG, "Scanning package " + pkg.packageName);
6568        }
6569
6570        if (mPackages.containsKey(pkg.packageName)
6571                || mSharedLibraries.containsKey(pkg.packageName)) {
6572            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6573                    "Application package " + pkg.packageName
6574                    + " already installed.  Skipping duplicate.");
6575        }
6576
6577        // If we're only installing presumed-existing packages, require that the
6578        // scanned APK is both already known and at the path previously established
6579        // for it.  Previously unknown packages we pick up normally, but if we have an
6580        // a priori expectation about this package's install presence, enforce it.
6581        // With a singular exception for new system packages. When an OTA contains
6582        // a new system package, we allow the codepath to change from a system location
6583        // to the user-installed location. If we don't allow this change, any newer,
6584        // user-installed version of the application will be ignored.
6585        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6586            if (mExpectingBetter.containsKey(pkg.packageName)) {
6587                logCriticalInfo(Log.WARN,
6588                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6589            } else {
6590                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6591                if (known != null) {
6592                    if (DEBUG_PACKAGE_SCANNING) {
6593                        Log.d(TAG, "Examining " + pkg.codePath
6594                                + " and requiring known paths " + known.codePathString
6595                                + " & " + known.resourcePathString);
6596                    }
6597                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6598                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6599                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6600                                "Application package " + pkg.packageName
6601                                + " found at " + pkg.applicationInfo.getCodePath()
6602                                + " but expected at " + known.codePathString + "; ignoring.");
6603                    }
6604                }
6605            }
6606        }
6607
6608        // Initialize package source and resource directories
6609        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6610        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6611
6612        SharedUserSetting suid = null;
6613        PackageSetting pkgSetting = null;
6614
6615        if (!isSystemApp(pkg)) {
6616            // Only system apps can use these features.
6617            pkg.mOriginalPackages = null;
6618            pkg.mRealPackage = null;
6619            pkg.mAdoptPermissions = null;
6620        }
6621
6622        // writer
6623        synchronized (mPackages) {
6624            if (pkg.mSharedUserId != null) {
6625                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6626                if (suid == null) {
6627                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6628                            "Creating application package " + pkg.packageName
6629                            + " for shared user failed");
6630                }
6631                if (DEBUG_PACKAGE_SCANNING) {
6632                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6633                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6634                                + "): packages=" + suid.packages);
6635                }
6636            }
6637
6638            // Check if we are renaming from an original package name.
6639            PackageSetting origPackage = null;
6640            String realName = null;
6641            if (pkg.mOriginalPackages != null) {
6642                // This package may need to be renamed to a previously
6643                // installed name.  Let's check on that...
6644                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6645                if (pkg.mOriginalPackages.contains(renamed)) {
6646                    // This package had originally been installed as the
6647                    // original name, and we have already taken care of
6648                    // transitioning to the new one.  Just update the new
6649                    // one to continue using the old name.
6650                    realName = pkg.mRealPackage;
6651                    if (!pkg.packageName.equals(renamed)) {
6652                        // Callers into this function may have already taken
6653                        // care of renaming the package; only do it here if
6654                        // it is not already done.
6655                        pkg.setPackageName(renamed);
6656                    }
6657
6658                } else {
6659                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6660                        if ((origPackage = mSettings.peekPackageLPr(
6661                                pkg.mOriginalPackages.get(i))) != null) {
6662                            // We do have the package already installed under its
6663                            // original name...  should we use it?
6664                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6665                                // New package is not compatible with original.
6666                                origPackage = null;
6667                                continue;
6668                            } else if (origPackage.sharedUser != null) {
6669                                // Make sure uid is compatible between packages.
6670                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6671                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6672                                            + " to " + pkg.packageName + ": old uid "
6673                                            + origPackage.sharedUser.name
6674                                            + " differs from " + pkg.mSharedUserId);
6675                                    origPackage = null;
6676                                    continue;
6677                                }
6678                            } else {
6679                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6680                                        + pkg.packageName + " to old name " + origPackage.name);
6681                            }
6682                            break;
6683                        }
6684                    }
6685                }
6686            }
6687
6688            if (mTransferedPackages.contains(pkg.packageName)) {
6689                Slog.w(TAG, "Package " + pkg.packageName
6690                        + " was transferred to another, but its .apk remains");
6691            }
6692
6693            // Just create the setting, don't add it yet. For already existing packages
6694            // the PkgSetting exists already and doesn't have to be created.
6695            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6696                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6697                    pkg.applicationInfo.primaryCpuAbi,
6698                    pkg.applicationInfo.secondaryCpuAbi,
6699                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6700                    user, false);
6701            if (pkgSetting == null) {
6702                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6703                        "Creating application package " + pkg.packageName + " failed");
6704            }
6705
6706            if (pkgSetting.origPackage != null) {
6707                // If we are first transitioning from an original package,
6708                // fix up the new package's name now.  We need to do this after
6709                // looking up the package under its new name, so getPackageLP
6710                // can take care of fiddling things correctly.
6711                pkg.setPackageName(origPackage.name);
6712
6713                // File a report about this.
6714                String msg = "New package " + pkgSetting.realName
6715                        + " renamed to replace old package " + pkgSetting.name;
6716                reportSettingsProblem(Log.WARN, msg);
6717
6718                // Make a note of it.
6719                mTransferedPackages.add(origPackage.name);
6720
6721                // No longer need to retain this.
6722                pkgSetting.origPackage = null;
6723            }
6724
6725            if (realName != null) {
6726                // Make a note of it.
6727                mTransferedPackages.add(pkg.packageName);
6728            }
6729
6730            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6731                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6732            }
6733
6734            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6735                // Check all shared libraries and map to their actual file path.
6736                // We only do this here for apps not on a system dir, because those
6737                // are the only ones that can fail an install due to this.  We
6738                // will take care of the system apps by updating all of their
6739                // library paths after the scan is done.
6740                updateSharedLibrariesLPw(pkg, null);
6741            }
6742
6743            if (mFoundPolicyFile) {
6744                SELinuxMMAC.assignSeinfoValue(pkg);
6745            }
6746
6747            pkg.applicationInfo.uid = pkgSetting.appId;
6748            pkg.mExtras = pkgSetting;
6749            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6750                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6751                    // We just determined the app is signed correctly, so bring
6752                    // over the latest parsed certs.
6753                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6754                } else {
6755                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6756                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6757                                "Package " + pkg.packageName + " upgrade keys do not match the "
6758                                + "previously installed version");
6759                    } else {
6760                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6761                        String msg = "System package " + pkg.packageName
6762                            + " signature changed; retaining data.";
6763                        reportSettingsProblem(Log.WARN, msg);
6764                    }
6765                }
6766            } else {
6767                try {
6768                    verifySignaturesLP(pkgSetting, pkg);
6769                    // We just determined the app is signed correctly, so bring
6770                    // over the latest parsed certs.
6771                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6772                } catch (PackageManagerException e) {
6773                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6774                        throw e;
6775                    }
6776                    // The signature has changed, but this package is in the system
6777                    // image...  let's recover!
6778                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6779                    // However...  if this package is part of a shared user, but it
6780                    // doesn't match the signature of the shared user, let's fail.
6781                    // What this means is that you can't change the signatures
6782                    // associated with an overall shared user, which doesn't seem all
6783                    // that unreasonable.
6784                    if (pkgSetting.sharedUser != null) {
6785                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6786                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6787                            throw new PackageManagerException(
6788                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6789                                            "Signature mismatch for shared user : "
6790                                            + pkgSetting.sharedUser);
6791                        }
6792                    }
6793                    // File a report about this.
6794                    String msg = "System package " + pkg.packageName
6795                        + " signature changed; retaining data.";
6796                    reportSettingsProblem(Log.WARN, msg);
6797                }
6798            }
6799            // Verify that this new package doesn't have any content providers
6800            // that conflict with existing packages.  Only do this if the
6801            // package isn't already installed, since we don't want to break
6802            // things that are installed.
6803            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6804                final int N = pkg.providers.size();
6805                int i;
6806                for (i=0; i<N; i++) {
6807                    PackageParser.Provider p = pkg.providers.get(i);
6808                    if (p.info.authority != null) {
6809                        String names[] = p.info.authority.split(";");
6810                        for (int j = 0; j < names.length; j++) {
6811                            if (mProvidersByAuthority.containsKey(names[j])) {
6812                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6813                                final String otherPackageName =
6814                                        ((other != null && other.getComponentName() != null) ?
6815                                                other.getComponentName().getPackageName() : "?");
6816                                throw new PackageManagerException(
6817                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6818                                                "Can't install because provider name " + names[j]
6819                                                + " (in package " + pkg.applicationInfo.packageName
6820                                                + ") is already used by " + otherPackageName);
6821                            }
6822                        }
6823                    }
6824                }
6825            }
6826
6827            if (pkg.mAdoptPermissions != null) {
6828                // This package wants to adopt ownership of permissions from
6829                // another package.
6830                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6831                    final String origName = pkg.mAdoptPermissions.get(i);
6832                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6833                    if (orig != null) {
6834                        if (verifyPackageUpdateLPr(orig, pkg)) {
6835                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6836                                    + pkg.packageName);
6837                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6838                        }
6839                    }
6840                }
6841            }
6842        }
6843
6844        final String pkgName = pkg.packageName;
6845
6846        final long scanFileTime = scanFile.lastModified();
6847        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6848        pkg.applicationInfo.processName = fixProcessName(
6849                pkg.applicationInfo.packageName,
6850                pkg.applicationInfo.processName,
6851                pkg.applicationInfo.uid);
6852
6853        File dataPath;
6854        if (mPlatformPackage == pkg) {
6855            // The system package is special.
6856            dataPath = new File(Environment.getDataDirectory(), "system");
6857
6858            pkg.applicationInfo.dataDir = dataPath.getPath();
6859
6860        } else {
6861            // This is a normal package, need to make its data directory.
6862            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6863                    UserHandle.USER_OWNER, pkg.packageName);
6864
6865            boolean uidError = false;
6866            if (dataPath.exists()) {
6867                int currentUid = 0;
6868                try {
6869                    StructStat stat = Os.stat(dataPath.getPath());
6870                    currentUid = stat.st_uid;
6871                } catch (ErrnoException e) {
6872                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6873                }
6874
6875                // If we have mismatched owners for the data path, we have a problem.
6876                if (currentUid != pkg.applicationInfo.uid) {
6877                    boolean recovered = false;
6878                    if (currentUid == 0) {
6879                        // The directory somehow became owned by root.  Wow.
6880                        // This is probably because the system was stopped while
6881                        // installd was in the middle of messing with its libs
6882                        // directory.  Ask installd to fix that.
6883                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6884                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6885                        if (ret >= 0) {
6886                            recovered = true;
6887                            String msg = "Package " + pkg.packageName
6888                                    + " unexpectedly changed to uid 0; recovered to " +
6889                                    + pkg.applicationInfo.uid;
6890                            reportSettingsProblem(Log.WARN, msg);
6891                        }
6892                    }
6893                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6894                            || (scanFlags&SCAN_BOOTING) != 0)) {
6895                        // If this is a system app, we can at least delete its
6896                        // current data so the application will still work.
6897                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6898                        if (ret >= 0) {
6899                            // TODO: Kill the processes first
6900                            // Old data gone!
6901                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6902                                    ? "System package " : "Third party package ";
6903                            String msg = prefix + pkg.packageName
6904                                    + " has changed from uid: "
6905                                    + currentUid + " to "
6906                                    + pkg.applicationInfo.uid + "; old data erased";
6907                            reportSettingsProblem(Log.WARN, msg);
6908                            recovered = true;
6909
6910                            // And now re-install the app.
6911                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6912                                    pkg.applicationInfo.seinfo);
6913                            if (ret == -1) {
6914                                // Ack should not happen!
6915                                msg = prefix + pkg.packageName
6916                                        + " could not have data directory re-created after delete.";
6917                                reportSettingsProblem(Log.WARN, msg);
6918                                throw new PackageManagerException(
6919                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6920                            }
6921                        }
6922                        if (!recovered) {
6923                            mHasSystemUidErrors = true;
6924                        }
6925                    } else if (!recovered) {
6926                        // If we allow this install to proceed, we will be broken.
6927                        // Abort, abort!
6928                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6929                                "scanPackageLI");
6930                    }
6931                    if (!recovered) {
6932                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6933                            + pkg.applicationInfo.uid + "/fs_"
6934                            + currentUid;
6935                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6936                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6937                        String msg = "Package " + pkg.packageName
6938                                + " has mismatched uid: "
6939                                + currentUid + " on disk, "
6940                                + pkg.applicationInfo.uid + " in settings";
6941                        // writer
6942                        synchronized (mPackages) {
6943                            mSettings.mReadMessages.append(msg);
6944                            mSettings.mReadMessages.append('\n');
6945                            uidError = true;
6946                            if (!pkgSetting.uidError) {
6947                                reportSettingsProblem(Log.ERROR, msg);
6948                            }
6949                        }
6950                    }
6951                }
6952                pkg.applicationInfo.dataDir = dataPath.getPath();
6953                if (mShouldRestoreconData) {
6954                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6955                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6956                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6957                }
6958            } else {
6959                if (DEBUG_PACKAGE_SCANNING) {
6960                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6961                        Log.v(TAG, "Want this data dir: " + dataPath);
6962                }
6963                //invoke installer to do the actual installation
6964                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6965                        pkg.applicationInfo.seinfo);
6966                if (ret < 0) {
6967                    // Error from installer
6968                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6969                            "Unable to create data dirs [errorCode=" + ret + "]");
6970                }
6971
6972                if (dataPath.exists()) {
6973                    pkg.applicationInfo.dataDir = dataPath.getPath();
6974                } else {
6975                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6976                    pkg.applicationInfo.dataDir = null;
6977                }
6978            }
6979
6980            pkgSetting.uidError = uidError;
6981        }
6982
6983        final String path = scanFile.getPath();
6984        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6985
6986        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6987            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6988
6989            // Some system apps still use directory structure for native libraries
6990            // in which case we might end up not detecting abi solely based on apk
6991            // structure. Try to detect abi based on directory structure.
6992            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6993                    pkg.applicationInfo.primaryCpuAbi == null) {
6994                setBundledAppAbisAndRoots(pkg, pkgSetting);
6995                setNativeLibraryPaths(pkg);
6996            }
6997
6998        } else {
6999            if ((scanFlags & SCAN_MOVE) != 0) {
7000                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7001                // but we already have this packages package info in the PackageSetting. We just
7002                // use that and derive the native library path based on the new codepath.
7003                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7004                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7005            }
7006
7007            // Set native library paths again. For moves, the path will be updated based on the
7008            // ABIs we've determined above. For non-moves, the path will be updated based on the
7009            // ABIs we determined during compilation, but the path will depend on the final
7010            // package path (after the rename away from the stage path).
7011            setNativeLibraryPaths(pkg);
7012        }
7013
7014        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7015        final int[] userIds = sUserManager.getUserIds();
7016        synchronized (mInstallLock) {
7017            // Make sure all user data directories are ready to roll; we're okay
7018            // if they already exist
7019            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7020                for (int userId : userIds) {
7021                    if (userId != 0) {
7022                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7023                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7024                                pkg.applicationInfo.seinfo);
7025                    }
7026                }
7027            }
7028
7029            // Create a native library symlink only if we have native libraries
7030            // and if the native libraries are 32 bit libraries. We do not provide
7031            // this symlink for 64 bit libraries.
7032            if (pkg.applicationInfo.primaryCpuAbi != null &&
7033                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7034                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7035                for (int userId : userIds) {
7036                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7037                            nativeLibPath, userId) < 0) {
7038                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7039                                "Failed linking native library dir (user=" + userId + ")");
7040                    }
7041                }
7042            }
7043        }
7044
7045        // This is a special case for the "system" package, where the ABI is
7046        // dictated by the zygote configuration (and init.rc). We should keep track
7047        // of this ABI so that we can deal with "normal" applications that run under
7048        // the same UID correctly.
7049        if (mPlatformPackage == pkg) {
7050            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7051                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7052        }
7053
7054        // If there's a mismatch between the abi-override in the package setting
7055        // and the abiOverride specified for the install. Warn about this because we
7056        // would've already compiled the app without taking the package setting into
7057        // account.
7058        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7059            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7060                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7061                        " for package: " + pkg.packageName);
7062            }
7063        }
7064
7065        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7066        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7067        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7068
7069        // Copy the derived override back to the parsed package, so that we can
7070        // update the package settings accordingly.
7071        pkg.cpuAbiOverride = cpuAbiOverride;
7072
7073        if (DEBUG_ABI_SELECTION) {
7074            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7075                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7076                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7077        }
7078
7079        // Push the derived path down into PackageSettings so we know what to
7080        // clean up at uninstall time.
7081        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7082
7083        if (DEBUG_ABI_SELECTION) {
7084            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7085                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7086                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7087        }
7088
7089        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7090            // We don't do this here during boot because we can do it all
7091            // at once after scanning all existing packages.
7092            //
7093            // We also do this *before* we perform dexopt on this package, so that
7094            // we can avoid redundant dexopts, and also to make sure we've got the
7095            // code and package path correct.
7096            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7097                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7098        }
7099
7100        if ((scanFlags & SCAN_NO_DEX) == 0) {
7101            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7102                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7103                    (scanFlags & SCAN_BOOTING) == 0);
7104            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7105                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7106            }
7107        }
7108        if (mFactoryTest && pkg.requestedPermissions.contains(
7109                android.Manifest.permission.FACTORY_TEST)) {
7110            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7111        }
7112
7113        ArrayList<PackageParser.Package> clientLibPkgs = null;
7114
7115        // writer
7116        synchronized (mPackages) {
7117            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7118                // Only system apps can add new shared libraries.
7119                if (pkg.libraryNames != null) {
7120                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7121                        String name = pkg.libraryNames.get(i);
7122                        boolean allowed = false;
7123                        if (pkg.isUpdatedSystemApp()) {
7124                            // New library entries can only be added through the
7125                            // system image.  This is important to get rid of a lot
7126                            // of nasty edge cases: for example if we allowed a non-
7127                            // system update of the app to add a library, then uninstalling
7128                            // the update would make the library go away, and assumptions
7129                            // we made such as through app install filtering would now
7130                            // have allowed apps on the device which aren't compatible
7131                            // with it.  Better to just have the restriction here, be
7132                            // conservative, and create many fewer cases that can negatively
7133                            // impact the user experience.
7134                            final PackageSetting sysPs = mSettings
7135                                    .getDisabledSystemPkgLPr(pkg.packageName);
7136                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7137                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7138                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7139                                        allowed = true;
7140                                        allowed = true;
7141                                        break;
7142                                    }
7143                                }
7144                            }
7145                        } else {
7146                            allowed = true;
7147                        }
7148                        if (allowed) {
7149                            if (!mSharedLibraries.containsKey(name)) {
7150                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7151                            } else if (!name.equals(pkg.packageName)) {
7152                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7153                                        + name + " already exists; skipping");
7154                            }
7155                        } else {
7156                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7157                                    + name + " that is not declared on system image; skipping");
7158                        }
7159                    }
7160                    if ((scanFlags&SCAN_BOOTING) == 0) {
7161                        // If we are not booting, we need to update any applications
7162                        // that are clients of our shared library.  If we are booting,
7163                        // this will all be done once the scan is complete.
7164                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7165                    }
7166                }
7167            }
7168        }
7169
7170        // We also need to dexopt any apps that are dependent on this library.  Note that
7171        // if these fail, we should abort the install since installing the library will
7172        // result in some apps being broken.
7173        if (clientLibPkgs != null) {
7174            if ((scanFlags & SCAN_NO_DEX) == 0) {
7175                for (int i = 0; i < clientLibPkgs.size(); i++) {
7176                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7177                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7178                            null /* instruction sets */, forceDex,
7179                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7180                            (scanFlags & SCAN_BOOTING) == 0);
7181                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7182                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7183                                "scanPackageLI failed to dexopt clientLibPkgs");
7184                    }
7185                }
7186            }
7187        }
7188
7189        // Request the ActivityManager to kill the process(only for existing packages)
7190        // so that we do not end up in a confused state while the user is still using the older
7191        // version of the application while the new one gets installed.
7192        if ((scanFlags & SCAN_REPLACING) != 0) {
7193            killApplication(pkg.applicationInfo.packageName,
7194                        pkg.applicationInfo.uid, "replace pkg");
7195        }
7196
7197        // Also need to kill any apps that are dependent on the library.
7198        if (clientLibPkgs != null) {
7199            for (int i=0; i<clientLibPkgs.size(); i++) {
7200                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7201                killApplication(clientPkg.applicationInfo.packageName,
7202                        clientPkg.applicationInfo.uid, "update lib");
7203            }
7204        }
7205
7206        // Make sure we're not adding any bogus keyset info
7207        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7208        ksms.assertScannedPackageValid(pkg);
7209
7210        // writer
7211        synchronized (mPackages) {
7212            // We don't expect installation to fail beyond this point
7213
7214            // Add the new setting to mSettings
7215            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7216            // Add the new setting to mPackages
7217            mPackages.put(pkg.applicationInfo.packageName, pkg);
7218            // Make sure we don't accidentally delete its data.
7219            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7220            while (iter.hasNext()) {
7221                PackageCleanItem item = iter.next();
7222                if (pkgName.equals(item.packageName)) {
7223                    iter.remove();
7224                }
7225            }
7226
7227            // Take care of first install / last update times.
7228            if (currentTime != 0) {
7229                if (pkgSetting.firstInstallTime == 0) {
7230                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7231                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7232                    pkgSetting.lastUpdateTime = currentTime;
7233                }
7234            } else if (pkgSetting.firstInstallTime == 0) {
7235                // We need *something*.  Take time time stamp of the file.
7236                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7237            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7238                if (scanFileTime != pkgSetting.timeStamp) {
7239                    // A package on the system image has changed; consider this
7240                    // to be an update.
7241                    pkgSetting.lastUpdateTime = scanFileTime;
7242                }
7243            }
7244
7245            // Add the package's KeySets to the global KeySetManagerService
7246            ksms.addScannedPackageLPw(pkg);
7247
7248            int N = pkg.providers.size();
7249            StringBuilder r = null;
7250            int i;
7251            for (i=0; i<N; i++) {
7252                PackageParser.Provider p = pkg.providers.get(i);
7253                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7254                        p.info.processName, pkg.applicationInfo.uid);
7255                mProviders.addProvider(p);
7256                p.syncable = p.info.isSyncable;
7257                if (p.info.authority != null) {
7258                    String names[] = p.info.authority.split(";");
7259                    p.info.authority = null;
7260                    for (int j = 0; j < names.length; j++) {
7261                        if (j == 1 && p.syncable) {
7262                            // We only want the first authority for a provider to possibly be
7263                            // syncable, so if we already added this provider using a different
7264                            // authority clear the syncable flag. We copy the provider before
7265                            // changing it because the mProviders object contains a reference
7266                            // to a provider that we don't want to change.
7267                            // Only do this for the second authority since the resulting provider
7268                            // object can be the same for all future authorities for this provider.
7269                            p = new PackageParser.Provider(p);
7270                            p.syncable = false;
7271                        }
7272                        if (!mProvidersByAuthority.containsKey(names[j])) {
7273                            mProvidersByAuthority.put(names[j], p);
7274                            if (p.info.authority == null) {
7275                                p.info.authority = names[j];
7276                            } else {
7277                                p.info.authority = p.info.authority + ";" + names[j];
7278                            }
7279                            if (DEBUG_PACKAGE_SCANNING) {
7280                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7281                                    Log.d(TAG, "Registered content provider: " + names[j]
7282                                            + ", className = " + p.info.name + ", isSyncable = "
7283                                            + p.info.isSyncable);
7284                            }
7285                        } else {
7286                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7287                            Slog.w(TAG, "Skipping provider name " + names[j] +
7288                                    " (in package " + pkg.applicationInfo.packageName +
7289                                    "): name already used by "
7290                                    + ((other != null && other.getComponentName() != null)
7291                                            ? other.getComponentName().getPackageName() : "?"));
7292                        }
7293                    }
7294                }
7295                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7296                    if (r == null) {
7297                        r = new StringBuilder(256);
7298                    } else {
7299                        r.append(' ');
7300                    }
7301                    r.append(p.info.name);
7302                }
7303            }
7304            if (r != null) {
7305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7306            }
7307
7308            N = pkg.services.size();
7309            r = null;
7310            for (i=0; i<N; i++) {
7311                PackageParser.Service s = pkg.services.get(i);
7312                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7313                        s.info.processName, pkg.applicationInfo.uid);
7314                mServices.addService(s);
7315                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7316                    if (r == null) {
7317                        r = new StringBuilder(256);
7318                    } else {
7319                        r.append(' ');
7320                    }
7321                    r.append(s.info.name);
7322                }
7323            }
7324            if (r != null) {
7325                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7326            }
7327
7328            N = pkg.receivers.size();
7329            r = null;
7330            for (i=0; i<N; i++) {
7331                PackageParser.Activity a = pkg.receivers.get(i);
7332                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7333                        a.info.processName, pkg.applicationInfo.uid);
7334                mReceivers.addActivity(a, "receiver");
7335                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7336                    if (r == null) {
7337                        r = new StringBuilder(256);
7338                    } else {
7339                        r.append(' ');
7340                    }
7341                    r.append(a.info.name);
7342                }
7343            }
7344            if (r != null) {
7345                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7346            }
7347
7348            N = pkg.activities.size();
7349            r = null;
7350            for (i=0; i<N; i++) {
7351                PackageParser.Activity a = pkg.activities.get(i);
7352                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7353                        a.info.processName, pkg.applicationInfo.uid);
7354                mActivities.addActivity(a, "activity");
7355                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7356                    if (r == null) {
7357                        r = new StringBuilder(256);
7358                    } else {
7359                        r.append(' ');
7360                    }
7361                    r.append(a.info.name);
7362                }
7363            }
7364            if (r != null) {
7365                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7366            }
7367
7368            N = pkg.permissionGroups.size();
7369            r = null;
7370            for (i=0; i<N; i++) {
7371                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7372                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7373                if (cur == null) {
7374                    mPermissionGroups.put(pg.info.name, pg);
7375                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7376                        if (r == null) {
7377                            r = new StringBuilder(256);
7378                        } else {
7379                            r.append(' ');
7380                        }
7381                        r.append(pg.info.name);
7382                    }
7383                } else {
7384                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7385                            + pg.info.packageName + " ignored: original from "
7386                            + cur.info.packageName);
7387                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7388                        if (r == null) {
7389                            r = new StringBuilder(256);
7390                        } else {
7391                            r.append(' ');
7392                        }
7393                        r.append("DUP:");
7394                        r.append(pg.info.name);
7395                    }
7396                }
7397            }
7398            if (r != null) {
7399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7400            }
7401
7402            N = pkg.permissions.size();
7403            r = null;
7404            for (i=0; i<N; i++) {
7405                PackageParser.Permission p = pkg.permissions.get(i);
7406
7407                // Assume by default that we did not install this permission into the system.
7408                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7409
7410                // Now that permission groups have a special meaning, we ignore permission
7411                // groups for legacy apps to prevent unexpected behavior. In particular,
7412                // permissions for one app being granted to someone just becuase they happen
7413                // to be in a group defined by another app (before this had no implications).
7414                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7415                    p.group = mPermissionGroups.get(p.info.group);
7416                    // Warn for a permission in an unknown group.
7417                    if (p.info.group != null && p.group == null) {
7418                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7419                                + p.info.packageName + " in an unknown group " + p.info.group);
7420                    }
7421                }
7422
7423                ArrayMap<String, BasePermission> permissionMap =
7424                        p.tree ? mSettings.mPermissionTrees
7425                                : mSettings.mPermissions;
7426                BasePermission bp = permissionMap.get(p.info.name);
7427
7428                // Allow system apps to redefine non-system permissions
7429                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7430                    final boolean currentOwnerIsSystem = (bp.perm != null
7431                            && isSystemApp(bp.perm.owner));
7432                    if (isSystemApp(p.owner)) {
7433                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7434                            // It's a built-in permission and no owner, take ownership now
7435                            bp.packageSetting = pkgSetting;
7436                            bp.perm = p;
7437                            bp.uid = pkg.applicationInfo.uid;
7438                            bp.sourcePackage = p.info.packageName;
7439                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7440                        } else if (!currentOwnerIsSystem) {
7441                            String msg = "New decl " + p.owner + " of permission  "
7442                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7443                            reportSettingsProblem(Log.WARN, msg);
7444                            bp = null;
7445                        }
7446                    }
7447                }
7448
7449                if (bp == null) {
7450                    bp = new BasePermission(p.info.name, p.info.packageName,
7451                            BasePermission.TYPE_NORMAL);
7452                    permissionMap.put(p.info.name, bp);
7453                }
7454
7455                if (bp.perm == null) {
7456                    if (bp.sourcePackage == null
7457                            || bp.sourcePackage.equals(p.info.packageName)) {
7458                        BasePermission tree = findPermissionTreeLP(p.info.name);
7459                        if (tree == null
7460                                || tree.sourcePackage.equals(p.info.packageName)) {
7461                            bp.packageSetting = pkgSetting;
7462                            bp.perm = p;
7463                            bp.uid = pkg.applicationInfo.uid;
7464                            bp.sourcePackage = p.info.packageName;
7465                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7466                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7467                                if (r == null) {
7468                                    r = new StringBuilder(256);
7469                                } else {
7470                                    r.append(' ');
7471                                }
7472                                r.append(p.info.name);
7473                            }
7474                        } else {
7475                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7476                                    + p.info.packageName + " ignored: base tree "
7477                                    + tree.name + " is from package "
7478                                    + tree.sourcePackage);
7479                        }
7480                    } else {
7481                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7482                                + p.info.packageName + " ignored: original from "
7483                                + bp.sourcePackage);
7484                    }
7485                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7486                    if (r == null) {
7487                        r = new StringBuilder(256);
7488                    } else {
7489                        r.append(' ');
7490                    }
7491                    r.append("DUP:");
7492                    r.append(p.info.name);
7493                }
7494                if (bp.perm == p) {
7495                    bp.protectionLevel = p.info.protectionLevel;
7496                }
7497            }
7498
7499            if (r != null) {
7500                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7501            }
7502
7503            N = pkg.instrumentation.size();
7504            r = null;
7505            for (i=0; i<N; i++) {
7506                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7507                a.info.packageName = pkg.applicationInfo.packageName;
7508                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7509                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7510                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7511                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7512                a.info.dataDir = pkg.applicationInfo.dataDir;
7513
7514                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7515                // need other information about the application, like the ABI and what not ?
7516                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7517                mInstrumentation.put(a.getComponentName(), a);
7518                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7519                    if (r == null) {
7520                        r = new StringBuilder(256);
7521                    } else {
7522                        r.append(' ');
7523                    }
7524                    r.append(a.info.name);
7525                }
7526            }
7527            if (r != null) {
7528                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7529            }
7530
7531            if (pkg.protectedBroadcasts != null) {
7532                N = pkg.protectedBroadcasts.size();
7533                for (i=0; i<N; i++) {
7534                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7535                }
7536            }
7537
7538            pkgSetting.setTimeStamp(scanFileTime);
7539
7540            // Create idmap files for pairs of (packages, overlay packages).
7541            // Note: "android", ie framework-res.apk, is handled by native layers.
7542            if (pkg.mOverlayTarget != null) {
7543                // This is an overlay package.
7544                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7545                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7546                        mOverlays.put(pkg.mOverlayTarget,
7547                                new ArrayMap<String, PackageParser.Package>());
7548                    }
7549                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7550                    map.put(pkg.packageName, pkg);
7551                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7552                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7553                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7554                                "scanPackageLI failed to createIdmap");
7555                    }
7556                }
7557            } else if (mOverlays.containsKey(pkg.packageName) &&
7558                    !pkg.packageName.equals("android")) {
7559                // This is a regular package, with one or more known overlay packages.
7560                createIdmapsForPackageLI(pkg);
7561            }
7562        }
7563
7564        return pkg;
7565    }
7566
7567    /**
7568     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7569     * is derived purely on the basis of the contents of {@code scanFile} and
7570     * {@code cpuAbiOverride}.
7571     *
7572     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7573     */
7574    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7575                                 String cpuAbiOverride, boolean extractLibs)
7576            throws PackageManagerException {
7577        // TODO: We can probably be smarter about this stuff. For installed apps,
7578        // we can calculate this information at install time once and for all. For
7579        // system apps, we can probably assume that this information doesn't change
7580        // after the first boot scan. As things stand, we do lots of unnecessary work.
7581
7582        // Give ourselves some initial paths; we'll come back for another
7583        // pass once we've determined ABI below.
7584        setNativeLibraryPaths(pkg);
7585
7586        // We would never need to extract libs for forward-locked and external packages,
7587        // since the container service will do it for us. We shouldn't attempt to
7588        // extract libs from system app when it was not updated.
7589        if (pkg.isForwardLocked() || isExternal(pkg) ||
7590            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7591            extractLibs = false;
7592        }
7593
7594        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7595        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7596
7597        NativeLibraryHelper.Handle handle = null;
7598        try {
7599            handle = NativeLibraryHelper.Handle.create(scanFile);
7600            // TODO(multiArch): This can be null for apps that didn't go through the
7601            // usual installation process. We can calculate it again, like we
7602            // do during install time.
7603            //
7604            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7605            // unnecessary.
7606            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7607
7608            // Null out the abis so that they can be recalculated.
7609            pkg.applicationInfo.primaryCpuAbi = null;
7610            pkg.applicationInfo.secondaryCpuAbi = null;
7611            if (isMultiArch(pkg.applicationInfo)) {
7612                // Warn if we've set an abiOverride for multi-lib packages..
7613                // By definition, we need to copy both 32 and 64 bit libraries for
7614                // such packages.
7615                if (pkg.cpuAbiOverride != null
7616                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7617                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7618                }
7619
7620                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7621                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7622                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7623                    if (extractLibs) {
7624                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7625                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7626                                useIsaSpecificSubdirs);
7627                    } else {
7628                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7629                    }
7630                }
7631
7632                maybeThrowExceptionForMultiArchCopy(
7633                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7634
7635                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7636                    if (extractLibs) {
7637                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7638                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7639                                useIsaSpecificSubdirs);
7640                    } else {
7641                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7642                    }
7643                }
7644
7645                maybeThrowExceptionForMultiArchCopy(
7646                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7647
7648                if (abi64 >= 0) {
7649                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7650                }
7651
7652                if (abi32 >= 0) {
7653                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7654                    if (abi64 >= 0) {
7655                        pkg.applicationInfo.secondaryCpuAbi = abi;
7656                    } else {
7657                        pkg.applicationInfo.primaryCpuAbi = abi;
7658                    }
7659                }
7660            } else {
7661                String[] abiList = (cpuAbiOverride != null) ?
7662                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7663
7664                // Enable gross and lame hacks for apps that are built with old
7665                // SDK tools. We must scan their APKs for renderscript bitcode and
7666                // not launch them if it's present. Don't bother checking on devices
7667                // that don't have 64 bit support.
7668                boolean needsRenderScriptOverride = false;
7669                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7670                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7671                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7672                    needsRenderScriptOverride = true;
7673                }
7674
7675                final int copyRet;
7676                if (extractLibs) {
7677                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7678                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7679                } else {
7680                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7681                }
7682
7683                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7684                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7685                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7686                }
7687
7688                if (copyRet >= 0) {
7689                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7690                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7691                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7692                } else if (needsRenderScriptOverride) {
7693                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7694                }
7695            }
7696        } catch (IOException ioe) {
7697            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7698        } finally {
7699            IoUtils.closeQuietly(handle);
7700        }
7701
7702        // Now that we've calculated the ABIs and determined if it's an internal app,
7703        // we will go ahead and populate the nativeLibraryPath.
7704        setNativeLibraryPaths(pkg);
7705    }
7706
7707    /**
7708     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7709     * i.e, so that all packages can be run inside a single process if required.
7710     *
7711     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7712     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7713     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7714     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7715     * updating a package that belongs to a shared user.
7716     *
7717     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7718     * adds unnecessary complexity.
7719     */
7720    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7721            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7722            boolean bootComplete) {
7723        String requiredInstructionSet = null;
7724        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7725            requiredInstructionSet = VMRuntime.getInstructionSet(
7726                     scannedPackage.applicationInfo.primaryCpuAbi);
7727        }
7728
7729        PackageSetting requirer = null;
7730        for (PackageSetting ps : packagesForUser) {
7731            // If packagesForUser contains scannedPackage, we skip it. This will happen
7732            // when scannedPackage is an update of an existing package. Without this check,
7733            // we will never be able to change the ABI of any package belonging to a shared
7734            // user, even if it's compatible with other packages.
7735            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7736                if (ps.primaryCpuAbiString == null) {
7737                    continue;
7738                }
7739
7740                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7741                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7742                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7743                    // this but there's not much we can do.
7744                    String errorMessage = "Instruction set mismatch, "
7745                            + ((requirer == null) ? "[caller]" : requirer)
7746                            + " requires " + requiredInstructionSet + " whereas " + ps
7747                            + " requires " + instructionSet;
7748                    Slog.w(TAG, errorMessage);
7749                }
7750
7751                if (requiredInstructionSet == null) {
7752                    requiredInstructionSet = instructionSet;
7753                    requirer = ps;
7754                }
7755            }
7756        }
7757
7758        if (requiredInstructionSet != null) {
7759            String adjustedAbi;
7760            if (requirer != null) {
7761                // requirer != null implies that either scannedPackage was null or that scannedPackage
7762                // did not require an ABI, in which case we have to adjust scannedPackage to match
7763                // the ABI of the set (which is the same as requirer's ABI)
7764                adjustedAbi = requirer.primaryCpuAbiString;
7765                if (scannedPackage != null) {
7766                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7767                }
7768            } else {
7769                // requirer == null implies that we're updating all ABIs in the set to
7770                // match scannedPackage.
7771                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7772            }
7773
7774            for (PackageSetting ps : packagesForUser) {
7775                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7776                    if (ps.primaryCpuAbiString != null) {
7777                        continue;
7778                    }
7779
7780                    ps.primaryCpuAbiString = adjustedAbi;
7781                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7782                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7783                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7784
7785                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7786                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7787                                bootComplete);
7788                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7789                            ps.primaryCpuAbiString = null;
7790                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7791                            return;
7792                        } else {
7793                            mInstaller.rmdex(ps.codePathString,
7794                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7795                        }
7796                    }
7797                }
7798            }
7799        }
7800    }
7801
7802    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7803        synchronized (mPackages) {
7804            mResolverReplaced = true;
7805            // Set up information for custom user intent resolution activity.
7806            mResolveActivity.applicationInfo = pkg.applicationInfo;
7807            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7808            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7809            mResolveActivity.processName = pkg.applicationInfo.packageName;
7810            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7811            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7812                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7813            mResolveActivity.theme = 0;
7814            mResolveActivity.exported = true;
7815            mResolveActivity.enabled = true;
7816            mResolveInfo.activityInfo = mResolveActivity;
7817            mResolveInfo.priority = 0;
7818            mResolveInfo.preferredOrder = 0;
7819            mResolveInfo.match = 0;
7820            mResolveComponentName = mCustomResolverComponentName;
7821            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7822                    mResolveComponentName);
7823        }
7824    }
7825
7826    private static String calculateBundledApkRoot(final String codePathString) {
7827        final File codePath = new File(codePathString);
7828        final File codeRoot;
7829        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7830            codeRoot = Environment.getRootDirectory();
7831        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7832            codeRoot = Environment.getOemDirectory();
7833        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7834            codeRoot = Environment.getVendorDirectory();
7835        } else {
7836            // Unrecognized code path; take its top real segment as the apk root:
7837            // e.g. /something/app/blah.apk => /something
7838            try {
7839                File f = codePath.getCanonicalFile();
7840                File parent = f.getParentFile();    // non-null because codePath is a file
7841                File tmp;
7842                while ((tmp = parent.getParentFile()) != null) {
7843                    f = parent;
7844                    parent = tmp;
7845                }
7846                codeRoot = f;
7847                Slog.w(TAG, "Unrecognized code path "
7848                        + codePath + " - using " + codeRoot);
7849            } catch (IOException e) {
7850                // Can't canonicalize the code path -- shenanigans?
7851                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7852                return Environment.getRootDirectory().getPath();
7853            }
7854        }
7855        return codeRoot.getPath();
7856    }
7857
7858    /**
7859     * Derive and set the location of native libraries for the given package,
7860     * which varies depending on where and how the package was installed.
7861     */
7862    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7863        final ApplicationInfo info = pkg.applicationInfo;
7864        final String codePath = pkg.codePath;
7865        final File codeFile = new File(codePath);
7866        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7867        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7868
7869        info.nativeLibraryRootDir = null;
7870        info.nativeLibraryRootRequiresIsa = false;
7871        info.nativeLibraryDir = null;
7872        info.secondaryNativeLibraryDir = null;
7873
7874        if (isApkFile(codeFile)) {
7875            // Monolithic install
7876            if (bundledApp) {
7877                // If "/system/lib64/apkname" exists, assume that is the per-package
7878                // native library directory to use; otherwise use "/system/lib/apkname".
7879                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7880                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7881                        getPrimaryInstructionSet(info));
7882
7883                // This is a bundled system app so choose the path based on the ABI.
7884                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7885                // is just the default path.
7886                final String apkName = deriveCodePathName(codePath);
7887                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7888                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7889                        apkName).getAbsolutePath();
7890
7891                if (info.secondaryCpuAbi != null) {
7892                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7893                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7894                            secondaryLibDir, apkName).getAbsolutePath();
7895                }
7896            } else if (asecApp) {
7897                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7898                        .getAbsolutePath();
7899            } else {
7900                final String apkName = deriveCodePathName(codePath);
7901                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7902                        .getAbsolutePath();
7903            }
7904
7905            info.nativeLibraryRootRequiresIsa = false;
7906            info.nativeLibraryDir = info.nativeLibraryRootDir;
7907        } else {
7908            // Cluster install
7909            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7910            info.nativeLibraryRootRequiresIsa = true;
7911
7912            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7913                    getPrimaryInstructionSet(info)).getAbsolutePath();
7914
7915            if (info.secondaryCpuAbi != null) {
7916                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7917                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7918            }
7919        }
7920    }
7921
7922    /**
7923     * Calculate the abis and roots for a bundled app. These can uniquely
7924     * be determined from the contents of the system partition, i.e whether
7925     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7926     * of this information, and instead assume that the system was built
7927     * sensibly.
7928     */
7929    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7930                                           PackageSetting pkgSetting) {
7931        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7932
7933        // If "/system/lib64/apkname" exists, assume that is the per-package
7934        // native library directory to use; otherwise use "/system/lib/apkname".
7935        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7936        setBundledAppAbi(pkg, apkRoot, apkName);
7937        // pkgSetting might be null during rescan following uninstall of updates
7938        // to a bundled app, so accommodate that possibility.  The settings in
7939        // that case will be established later from the parsed package.
7940        //
7941        // If the settings aren't null, sync them up with what we've just derived.
7942        // note that apkRoot isn't stored in the package settings.
7943        if (pkgSetting != null) {
7944            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7945            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7946        }
7947    }
7948
7949    /**
7950     * Deduces the ABI of a bundled app and sets the relevant fields on the
7951     * parsed pkg object.
7952     *
7953     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7954     *        under which system libraries are installed.
7955     * @param apkName the name of the installed package.
7956     */
7957    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7958        final File codeFile = new File(pkg.codePath);
7959
7960        final boolean has64BitLibs;
7961        final boolean has32BitLibs;
7962        if (isApkFile(codeFile)) {
7963            // Monolithic install
7964            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7965            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7966        } else {
7967            // Cluster install
7968            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7969            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7970                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7971                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7972                has64BitLibs = (new File(rootDir, isa)).exists();
7973            } else {
7974                has64BitLibs = false;
7975            }
7976            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7977                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7978                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7979                has32BitLibs = (new File(rootDir, isa)).exists();
7980            } else {
7981                has32BitLibs = false;
7982            }
7983        }
7984
7985        if (has64BitLibs && !has32BitLibs) {
7986            // The package has 64 bit libs, but not 32 bit libs. Its primary
7987            // ABI should be 64 bit. We can safely assume here that the bundled
7988            // native libraries correspond to the most preferred ABI in the list.
7989
7990            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7991            pkg.applicationInfo.secondaryCpuAbi = null;
7992        } else if (has32BitLibs && !has64BitLibs) {
7993            // The package has 32 bit libs but not 64 bit libs. Its primary
7994            // ABI should be 32 bit.
7995
7996            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7997            pkg.applicationInfo.secondaryCpuAbi = null;
7998        } else if (has32BitLibs && has64BitLibs) {
7999            // The application has both 64 and 32 bit bundled libraries. We check
8000            // here that the app declares multiArch support, and warn if it doesn't.
8001            //
8002            // We will be lenient here and record both ABIs. The primary will be the
8003            // ABI that's higher on the list, i.e, a device that's configured to prefer
8004            // 64 bit apps will see a 64 bit primary ABI,
8005
8006            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8007                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8008            }
8009
8010            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8011                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8012                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8013            } else {
8014                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8015                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8016            }
8017        } else {
8018            pkg.applicationInfo.primaryCpuAbi = null;
8019            pkg.applicationInfo.secondaryCpuAbi = null;
8020        }
8021    }
8022
8023    private void killApplication(String pkgName, int appId, String reason) {
8024        // Request the ActivityManager to kill the process(only for existing packages)
8025        // so that we do not end up in a confused state while the user is still using the older
8026        // version of the application while the new one gets installed.
8027        IActivityManager am = ActivityManagerNative.getDefault();
8028        if (am != null) {
8029            try {
8030                am.killApplicationWithAppId(pkgName, appId, reason);
8031            } catch (RemoteException e) {
8032            }
8033        }
8034    }
8035
8036    void removePackageLI(PackageSetting ps, boolean chatty) {
8037        if (DEBUG_INSTALL) {
8038            if (chatty)
8039                Log.d(TAG, "Removing package " + ps.name);
8040        }
8041
8042        // writer
8043        synchronized (mPackages) {
8044            mPackages.remove(ps.name);
8045            final PackageParser.Package pkg = ps.pkg;
8046            if (pkg != null) {
8047                cleanPackageDataStructuresLILPw(pkg, chatty);
8048            }
8049        }
8050    }
8051
8052    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8053        if (DEBUG_INSTALL) {
8054            if (chatty)
8055                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8056        }
8057
8058        // writer
8059        synchronized (mPackages) {
8060            mPackages.remove(pkg.applicationInfo.packageName);
8061            cleanPackageDataStructuresLILPw(pkg, chatty);
8062        }
8063    }
8064
8065    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8066        int N = pkg.providers.size();
8067        StringBuilder r = null;
8068        int i;
8069        for (i=0; i<N; i++) {
8070            PackageParser.Provider p = pkg.providers.get(i);
8071            mProviders.removeProvider(p);
8072            if (p.info.authority == null) {
8073
8074                /* There was another ContentProvider with this authority when
8075                 * this app was installed so this authority is null,
8076                 * Ignore it as we don't have to unregister the provider.
8077                 */
8078                continue;
8079            }
8080            String names[] = p.info.authority.split(";");
8081            for (int j = 0; j < names.length; j++) {
8082                if (mProvidersByAuthority.get(names[j]) == p) {
8083                    mProvidersByAuthority.remove(names[j]);
8084                    if (DEBUG_REMOVE) {
8085                        if (chatty)
8086                            Log.d(TAG, "Unregistered content provider: " + names[j]
8087                                    + ", className = " + p.info.name + ", isSyncable = "
8088                                    + p.info.isSyncable);
8089                    }
8090                }
8091            }
8092            if (DEBUG_REMOVE && chatty) {
8093                if (r == null) {
8094                    r = new StringBuilder(256);
8095                } else {
8096                    r.append(' ');
8097                }
8098                r.append(p.info.name);
8099            }
8100        }
8101        if (r != null) {
8102            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8103        }
8104
8105        N = pkg.services.size();
8106        r = null;
8107        for (i=0; i<N; i++) {
8108            PackageParser.Service s = pkg.services.get(i);
8109            mServices.removeService(s);
8110            if (chatty) {
8111                if (r == null) {
8112                    r = new StringBuilder(256);
8113                } else {
8114                    r.append(' ');
8115                }
8116                r.append(s.info.name);
8117            }
8118        }
8119        if (r != null) {
8120            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8121        }
8122
8123        N = pkg.receivers.size();
8124        r = null;
8125        for (i=0; i<N; i++) {
8126            PackageParser.Activity a = pkg.receivers.get(i);
8127            mReceivers.removeActivity(a, "receiver");
8128            if (DEBUG_REMOVE && chatty) {
8129                if (r == null) {
8130                    r = new StringBuilder(256);
8131                } else {
8132                    r.append(' ');
8133                }
8134                r.append(a.info.name);
8135            }
8136        }
8137        if (r != null) {
8138            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8139        }
8140
8141        N = pkg.activities.size();
8142        r = null;
8143        for (i=0; i<N; i++) {
8144            PackageParser.Activity a = pkg.activities.get(i);
8145            mActivities.removeActivity(a, "activity");
8146            if (DEBUG_REMOVE && chatty) {
8147                if (r == null) {
8148                    r = new StringBuilder(256);
8149                } else {
8150                    r.append(' ');
8151                }
8152                r.append(a.info.name);
8153            }
8154        }
8155        if (r != null) {
8156            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8157        }
8158
8159        N = pkg.permissions.size();
8160        r = null;
8161        for (i=0; i<N; i++) {
8162            PackageParser.Permission p = pkg.permissions.get(i);
8163            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8164            if (bp == null) {
8165                bp = mSettings.mPermissionTrees.get(p.info.name);
8166            }
8167            if (bp != null && bp.perm == p) {
8168                bp.perm = null;
8169                if (DEBUG_REMOVE && chatty) {
8170                    if (r == null) {
8171                        r = new StringBuilder(256);
8172                    } else {
8173                        r.append(' ');
8174                    }
8175                    r.append(p.info.name);
8176                }
8177            }
8178            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8179                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8180                if (appOpPerms != null) {
8181                    appOpPerms.remove(pkg.packageName);
8182                }
8183            }
8184        }
8185        if (r != null) {
8186            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8187        }
8188
8189        N = pkg.requestedPermissions.size();
8190        r = null;
8191        for (i=0; i<N; i++) {
8192            String perm = pkg.requestedPermissions.get(i);
8193            BasePermission bp = mSettings.mPermissions.get(perm);
8194            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8195                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8196                if (appOpPerms != null) {
8197                    appOpPerms.remove(pkg.packageName);
8198                    if (appOpPerms.isEmpty()) {
8199                        mAppOpPermissionPackages.remove(perm);
8200                    }
8201                }
8202            }
8203        }
8204        if (r != null) {
8205            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8206        }
8207
8208        N = pkg.instrumentation.size();
8209        r = null;
8210        for (i=0; i<N; i++) {
8211            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8212            mInstrumentation.remove(a.getComponentName());
8213            if (DEBUG_REMOVE && chatty) {
8214                if (r == null) {
8215                    r = new StringBuilder(256);
8216                } else {
8217                    r.append(' ');
8218                }
8219                r.append(a.info.name);
8220            }
8221        }
8222        if (r != null) {
8223            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8224        }
8225
8226        r = null;
8227        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8228            // Only system apps can hold shared libraries.
8229            if (pkg.libraryNames != null) {
8230                for (i=0; i<pkg.libraryNames.size(); i++) {
8231                    String name = pkg.libraryNames.get(i);
8232                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8233                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8234                        mSharedLibraries.remove(name);
8235                        if (DEBUG_REMOVE && chatty) {
8236                            if (r == null) {
8237                                r = new StringBuilder(256);
8238                            } else {
8239                                r.append(' ');
8240                            }
8241                            r.append(name);
8242                        }
8243                    }
8244                }
8245            }
8246        }
8247        if (r != null) {
8248            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8249        }
8250    }
8251
8252    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8253        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8254            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8255                return true;
8256            }
8257        }
8258        return false;
8259    }
8260
8261    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8262    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8263    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8264
8265    private void updatePermissionsLPw(String changingPkg,
8266            PackageParser.Package pkgInfo, int flags) {
8267        // Make sure there are no dangling permission trees.
8268        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8269        while (it.hasNext()) {
8270            final BasePermission bp = it.next();
8271            if (bp.packageSetting == null) {
8272                // We may not yet have parsed the package, so just see if
8273                // we still know about its settings.
8274                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8275            }
8276            if (bp.packageSetting == null) {
8277                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8278                        + " from package " + bp.sourcePackage);
8279                it.remove();
8280            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8281                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8282                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8283                            + " from package " + bp.sourcePackage);
8284                    flags |= UPDATE_PERMISSIONS_ALL;
8285                    it.remove();
8286                }
8287            }
8288        }
8289
8290        // Make sure all dynamic permissions have been assigned to a package,
8291        // and make sure there are no dangling permissions.
8292        it = mSettings.mPermissions.values().iterator();
8293        while (it.hasNext()) {
8294            final BasePermission bp = it.next();
8295            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8296                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8297                        + bp.name + " pkg=" + bp.sourcePackage
8298                        + " info=" + bp.pendingInfo);
8299                if (bp.packageSetting == null && bp.pendingInfo != null) {
8300                    final BasePermission tree = findPermissionTreeLP(bp.name);
8301                    if (tree != null && tree.perm != null) {
8302                        bp.packageSetting = tree.packageSetting;
8303                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8304                                new PermissionInfo(bp.pendingInfo));
8305                        bp.perm.info.packageName = tree.perm.info.packageName;
8306                        bp.perm.info.name = bp.name;
8307                        bp.uid = tree.uid;
8308                    }
8309                }
8310            }
8311            if (bp.packageSetting == null) {
8312                // We may not yet have parsed the package, so just see if
8313                // we still know about its settings.
8314                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8315            }
8316            if (bp.packageSetting == null) {
8317                Slog.w(TAG, "Removing dangling permission: " + bp.name
8318                        + " from package " + bp.sourcePackage);
8319                it.remove();
8320            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8321                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8322                    Slog.i(TAG, "Removing old permission: " + bp.name
8323                            + " from package " + bp.sourcePackage);
8324                    flags |= UPDATE_PERMISSIONS_ALL;
8325                    it.remove();
8326                }
8327            }
8328        }
8329
8330        // Now update the permissions for all packages, in particular
8331        // replace the granted permissions of the system packages.
8332        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8333            for (PackageParser.Package pkg : mPackages.values()) {
8334                if (pkg != pkgInfo) {
8335                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8336                            changingPkg);
8337                }
8338            }
8339        }
8340
8341        if (pkgInfo != null) {
8342            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8343        }
8344    }
8345
8346    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8347            String packageOfInterest) {
8348        // IMPORTANT: There are two types of permissions: install and runtime.
8349        // Install time permissions are granted when the app is installed to
8350        // all device users and users added in the future. Runtime permissions
8351        // are granted at runtime explicitly to specific users. Normal and signature
8352        // protected permissions are install time permissions. Dangerous permissions
8353        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8354        // otherwise they are runtime permissions. This function does not manage
8355        // runtime permissions except for the case an app targeting Lollipop MR1
8356        // being upgraded to target a newer SDK, in which case dangerous permissions
8357        // are transformed from install time to runtime ones.
8358
8359        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8360        if (ps == null) {
8361            return;
8362        }
8363
8364        PermissionsState permissionsState = ps.getPermissionsState();
8365        PermissionsState origPermissions = permissionsState;
8366
8367        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8368
8369        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8370
8371        boolean changedInstallPermission = false;
8372
8373        if (replace) {
8374            ps.installPermissionsFixed = false;
8375            if (!ps.isSharedUser()) {
8376                origPermissions = new PermissionsState(permissionsState);
8377                permissionsState.reset();
8378            }
8379        }
8380
8381        permissionsState.setGlobalGids(mGlobalGids);
8382
8383        final int N = pkg.requestedPermissions.size();
8384        for (int i=0; i<N; i++) {
8385            final String name = pkg.requestedPermissions.get(i);
8386            final BasePermission bp = mSettings.mPermissions.get(name);
8387
8388            if (DEBUG_INSTALL) {
8389                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8390            }
8391
8392            if (bp == null || bp.packageSetting == null) {
8393                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8394                    Slog.w(TAG, "Unknown permission " + name
8395                            + " in package " + pkg.packageName);
8396                }
8397                continue;
8398            }
8399
8400            final String perm = bp.name;
8401            boolean allowedSig = false;
8402            int grant = GRANT_DENIED;
8403
8404            // Keep track of app op permissions.
8405            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8406                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8407                if (pkgs == null) {
8408                    pkgs = new ArraySet<>();
8409                    mAppOpPermissionPackages.put(bp.name, pkgs);
8410                }
8411                pkgs.add(pkg.packageName);
8412            }
8413
8414            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8415            switch (level) {
8416                case PermissionInfo.PROTECTION_NORMAL: {
8417                    // For all apps normal permissions are install time ones.
8418                    grant = GRANT_INSTALL;
8419                } break;
8420
8421                case PermissionInfo.PROTECTION_DANGEROUS: {
8422                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8423                        // For legacy apps dangerous permissions are install time ones.
8424                        grant = GRANT_INSTALL_LEGACY;
8425                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8426                        // For legacy apps that became modern, install becomes runtime.
8427                        grant = GRANT_UPGRADE;
8428                    } else if (mPromoteSystemApps
8429                            && isSystemApp(ps)
8430                            && mExistingSystemPackages.contains(ps.name)) {
8431                        // For legacy system apps, install becomes runtime.
8432                        // We cannot check hasInstallPermission() for system apps since those
8433                        // permissions were granted implicitly and not persisted pre-M.
8434                        grant = GRANT_UPGRADE;
8435                    } else {
8436                        // For modern apps keep runtime permissions unchanged.
8437                        grant = GRANT_RUNTIME;
8438                    }
8439                } break;
8440
8441                case PermissionInfo.PROTECTION_SIGNATURE: {
8442                    // For all apps signature permissions are install time ones.
8443                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8444                    if (allowedSig) {
8445                        grant = GRANT_INSTALL;
8446                    }
8447                } break;
8448            }
8449
8450            if (DEBUG_INSTALL) {
8451                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8452            }
8453
8454            if (grant != GRANT_DENIED) {
8455                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8456                    // If this is an existing, non-system package, then
8457                    // we can't add any new permissions to it.
8458                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8459                        // Except...  if this is a permission that was added
8460                        // to the platform (note: need to only do this when
8461                        // updating the platform).
8462                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8463                            grant = GRANT_DENIED;
8464                        }
8465                    }
8466                }
8467
8468                switch (grant) {
8469                    case GRANT_INSTALL: {
8470                        // Revoke this as runtime permission to handle the case of
8471                        // a runtime permission being downgraded to an install one.
8472                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8473                            if (origPermissions.getRuntimePermissionState(
8474                                    bp.name, userId) != null) {
8475                                // Revoke the runtime permission and clear the flags.
8476                                origPermissions.revokeRuntimePermission(bp, userId);
8477                                origPermissions.updatePermissionFlags(bp, userId,
8478                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8479                                // If we revoked a permission permission, we have to write.
8480                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8481                                        changedRuntimePermissionUserIds, userId);
8482                            }
8483                        }
8484                        // Grant an install permission.
8485                        if (permissionsState.grantInstallPermission(bp) !=
8486                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8487                            changedInstallPermission = true;
8488                        }
8489                    } break;
8490
8491                    case GRANT_INSTALL_LEGACY: {
8492                        // Grant an install permission.
8493                        if (permissionsState.grantInstallPermission(bp) !=
8494                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8495                            changedInstallPermission = true;
8496                        }
8497                    } break;
8498
8499                    case GRANT_RUNTIME: {
8500                        // Grant previously granted runtime permissions.
8501                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8502                            PermissionState permissionState = origPermissions
8503                                    .getRuntimePermissionState(bp.name, userId);
8504                            final int flags = permissionState != null
8505                                    ? permissionState.getFlags() : 0;
8506                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8507                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8508                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8509                                    // If we cannot put the permission as it was, we have to write.
8510                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8511                                            changedRuntimePermissionUserIds, userId);
8512                                }
8513                            }
8514                            // Propagate the permission flags.
8515                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8516                        }
8517                    } break;
8518
8519                    case GRANT_UPGRADE: {
8520                        // Grant runtime permissions for a previously held install permission.
8521                        PermissionState permissionState = origPermissions
8522                                .getInstallPermissionState(bp.name);
8523                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8524
8525                        if (origPermissions.revokeInstallPermission(bp)
8526                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8527                            // We will be transferring the permission flags, so clear them.
8528                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8529                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8530                            changedInstallPermission = true;
8531                        }
8532
8533                        // If the permission is not to be promoted to runtime we ignore it and
8534                        // also its other flags as they are not applicable to install permissions.
8535                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8536                            for (int userId : currentUserIds) {
8537                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8538                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8539                                    // Transfer the permission flags.
8540                                    permissionsState.updatePermissionFlags(bp, userId,
8541                                            flags, flags);
8542                                    // If we granted the permission, we have to write.
8543                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8544                                            changedRuntimePermissionUserIds, userId);
8545                                }
8546                            }
8547                        }
8548                    } break;
8549
8550                    default: {
8551                        if (packageOfInterest == null
8552                                || packageOfInterest.equals(pkg.packageName)) {
8553                            Slog.w(TAG, "Not granting permission " + perm
8554                                    + " to package " + pkg.packageName
8555                                    + " because it was previously installed without");
8556                        }
8557                    } break;
8558                }
8559            } else {
8560                if (permissionsState.revokeInstallPermission(bp) !=
8561                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8562                    // Also drop the permission flags.
8563                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8564                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8565                    changedInstallPermission = true;
8566                    Slog.i(TAG, "Un-granting permission " + perm
8567                            + " from package " + pkg.packageName
8568                            + " (protectionLevel=" + bp.protectionLevel
8569                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8570                            + ")");
8571                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8572                    // Don't print warning for app op permissions, since it is fine for them
8573                    // not to be granted, there is a UI for the user to decide.
8574                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8575                        Slog.w(TAG, "Not granting permission " + perm
8576                                + " to package " + pkg.packageName
8577                                + " (protectionLevel=" + bp.protectionLevel
8578                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8579                                + ")");
8580                    }
8581                }
8582            }
8583        }
8584
8585        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8586                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8587            // This is the first that we have heard about this package, so the
8588            // permissions we have now selected are fixed until explicitly
8589            // changed.
8590            ps.installPermissionsFixed = true;
8591        }
8592
8593        // Persist the runtime permissions state for users with changes.
8594        for (int userId : changedRuntimePermissionUserIds) {
8595            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8596        }
8597    }
8598
8599    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8600        boolean allowed = false;
8601        final int NP = PackageParser.NEW_PERMISSIONS.length;
8602        for (int ip=0; ip<NP; ip++) {
8603            final PackageParser.NewPermissionInfo npi
8604                    = PackageParser.NEW_PERMISSIONS[ip];
8605            if (npi.name.equals(perm)
8606                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8607                allowed = true;
8608                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8609                        + pkg.packageName);
8610                break;
8611            }
8612        }
8613        return allowed;
8614    }
8615
8616    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8617            BasePermission bp, PermissionsState origPermissions) {
8618        boolean allowed;
8619        allowed = (compareSignatures(
8620                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8621                        == PackageManager.SIGNATURE_MATCH)
8622                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8623                        == PackageManager.SIGNATURE_MATCH);
8624        if (!allowed && (bp.protectionLevel
8625                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8626            if (isSystemApp(pkg)) {
8627                // For updated system applications, a system permission
8628                // is granted only if it had been defined by the original application.
8629                if (pkg.isUpdatedSystemApp()) {
8630                    final PackageSetting sysPs = mSettings
8631                            .getDisabledSystemPkgLPr(pkg.packageName);
8632                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8633                        // If the original was granted this permission, we take
8634                        // that grant decision as read and propagate it to the
8635                        // update.
8636                        if (sysPs.isPrivileged()) {
8637                            allowed = true;
8638                        }
8639                    } else {
8640                        // The system apk may have been updated with an older
8641                        // version of the one on the data partition, but which
8642                        // granted a new system permission that it didn't have
8643                        // before.  In this case we do want to allow the app to
8644                        // now get the new permission if the ancestral apk is
8645                        // privileged to get it.
8646                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8647                            for (int j=0;
8648                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8649                                if (perm.equals(
8650                                        sysPs.pkg.requestedPermissions.get(j))) {
8651                                    allowed = true;
8652                                    break;
8653                                }
8654                            }
8655                        }
8656                    }
8657                } else {
8658                    allowed = isPrivilegedApp(pkg);
8659                }
8660            }
8661        }
8662        if (!allowed) {
8663            if (!allowed && (bp.protectionLevel
8664                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8665                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8666                // If this was a previously normal/dangerous permission that got moved
8667                // to a system permission as part of the runtime permission redesign, then
8668                // we still want to blindly grant it to old apps.
8669                allowed = true;
8670            }
8671            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8672                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8673                // If this permission is to be granted to the system installer and
8674                // this app is an installer, then it gets the permission.
8675                allowed = true;
8676            }
8677            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8678                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8679                // If this permission is to be granted to the system verifier and
8680                // this app is a verifier, then it gets the permission.
8681                allowed = true;
8682            }
8683            if (!allowed && (bp.protectionLevel
8684                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8685                    && isSystemApp(pkg)) {
8686                // Any pre-installed system app is allowed to get this permission.
8687                allowed = true;
8688            }
8689            if (!allowed && (bp.protectionLevel
8690                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8691                // For development permissions, a development permission
8692                // is granted only if it was already granted.
8693                allowed = origPermissions.hasInstallPermission(perm);
8694            }
8695        }
8696        return allowed;
8697    }
8698
8699    final class ActivityIntentResolver
8700            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8701        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8702                boolean defaultOnly, int userId) {
8703            if (!sUserManager.exists(userId)) return null;
8704            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8705            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8706        }
8707
8708        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8709                int userId) {
8710            if (!sUserManager.exists(userId)) return null;
8711            mFlags = flags;
8712            return super.queryIntent(intent, resolvedType,
8713                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8714        }
8715
8716        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8717                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8718            if (!sUserManager.exists(userId)) return null;
8719            if (packageActivities == null) {
8720                return null;
8721            }
8722            mFlags = flags;
8723            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8724            final int N = packageActivities.size();
8725            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8726                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8727
8728            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8729            for (int i = 0; i < N; ++i) {
8730                intentFilters = packageActivities.get(i).intents;
8731                if (intentFilters != null && intentFilters.size() > 0) {
8732                    PackageParser.ActivityIntentInfo[] array =
8733                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8734                    intentFilters.toArray(array);
8735                    listCut.add(array);
8736                }
8737            }
8738            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8739        }
8740
8741        public final void addActivity(PackageParser.Activity a, String type) {
8742            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8743            mActivities.put(a.getComponentName(), a);
8744            if (DEBUG_SHOW_INFO)
8745                Log.v(
8746                TAG, "  " + type + " " +
8747                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8748            if (DEBUG_SHOW_INFO)
8749                Log.v(TAG, "    Class=" + a.info.name);
8750            final int NI = a.intents.size();
8751            for (int j=0; j<NI; j++) {
8752                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8753                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8754                    intent.setPriority(0);
8755                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8756                            + a.className + " with priority > 0, forcing to 0");
8757                }
8758                if (DEBUG_SHOW_INFO) {
8759                    Log.v(TAG, "    IntentFilter:");
8760                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8761                }
8762                if (!intent.debugCheck()) {
8763                    Log.w(TAG, "==> For Activity " + a.info.name);
8764                }
8765                addFilter(intent);
8766            }
8767        }
8768
8769        public final void removeActivity(PackageParser.Activity a, String type) {
8770            mActivities.remove(a.getComponentName());
8771            if (DEBUG_SHOW_INFO) {
8772                Log.v(TAG, "  " + type + " "
8773                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8774                                : a.info.name) + ":");
8775                Log.v(TAG, "    Class=" + a.info.name);
8776            }
8777            final int NI = a.intents.size();
8778            for (int j=0; j<NI; j++) {
8779                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8780                if (DEBUG_SHOW_INFO) {
8781                    Log.v(TAG, "    IntentFilter:");
8782                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8783                }
8784                removeFilter(intent);
8785            }
8786        }
8787
8788        @Override
8789        protected boolean allowFilterResult(
8790                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8791            ActivityInfo filterAi = filter.activity.info;
8792            for (int i=dest.size()-1; i>=0; i--) {
8793                ActivityInfo destAi = dest.get(i).activityInfo;
8794                if (destAi.name == filterAi.name
8795                        && destAi.packageName == filterAi.packageName) {
8796                    return false;
8797                }
8798            }
8799            return true;
8800        }
8801
8802        @Override
8803        protected ActivityIntentInfo[] newArray(int size) {
8804            return new ActivityIntentInfo[size];
8805        }
8806
8807        @Override
8808        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8809            if (!sUserManager.exists(userId)) return true;
8810            PackageParser.Package p = filter.activity.owner;
8811            if (p != null) {
8812                PackageSetting ps = (PackageSetting)p.mExtras;
8813                if (ps != null) {
8814                    // System apps are never considered stopped for purposes of
8815                    // filtering, because there may be no way for the user to
8816                    // actually re-launch them.
8817                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8818                            && ps.getStopped(userId);
8819                }
8820            }
8821            return false;
8822        }
8823
8824        @Override
8825        protected boolean isPackageForFilter(String packageName,
8826                PackageParser.ActivityIntentInfo info) {
8827            return packageName.equals(info.activity.owner.packageName);
8828        }
8829
8830        @Override
8831        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8832                int match, int userId) {
8833            if (!sUserManager.exists(userId)) return null;
8834            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8835                return null;
8836            }
8837            final PackageParser.Activity activity = info.activity;
8838            if (mSafeMode && (activity.info.applicationInfo.flags
8839                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8840                return null;
8841            }
8842            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8843            if (ps == null) {
8844                return null;
8845            }
8846            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8847                    ps.readUserState(userId), userId);
8848            if (ai == null) {
8849                return null;
8850            }
8851            final ResolveInfo res = new ResolveInfo();
8852            res.activityInfo = ai;
8853            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8854                res.filter = info;
8855            }
8856            if (info != null) {
8857                res.handleAllWebDataURI = info.handleAllWebDataURI();
8858            }
8859            res.priority = info.getPriority();
8860            res.preferredOrder = activity.owner.mPreferredOrder;
8861            //System.out.println("Result: " + res.activityInfo.className +
8862            //                   " = " + res.priority);
8863            res.match = match;
8864            res.isDefault = info.hasDefault;
8865            res.labelRes = info.labelRes;
8866            res.nonLocalizedLabel = info.nonLocalizedLabel;
8867            if (userNeedsBadging(userId)) {
8868                res.noResourceId = true;
8869            } else {
8870                res.icon = info.icon;
8871            }
8872            res.iconResourceId = info.icon;
8873            res.system = res.activityInfo.applicationInfo.isSystemApp();
8874            return res;
8875        }
8876
8877        @Override
8878        protected void sortResults(List<ResolveInfo> results) {
8879            Collections.sort(results, mResolvePrioritySorter);
8880        }
8881
8882        @Override
8883        protected void dumpFilter(PrintWriter out, String prefix,
8884                PackageParser.ActivityIntentInfo filter) {
8885            out.print(prefix); out.print(
8886                    Integer.toHexString(System.identityHashCode(filter.activity)));
8887                    out.print(' ');
8888                    filter.activity.printComponentShortName(out);
8889                    out.print(" filter ");
8890                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8891        }
8892
8893        @Override
8894        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8895            return filter.activity;
8896        }
8897
8898        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8899            PackageParser.Activity activity = (PackageParser.Activity)label;
8900            out.print(prefix); out.print(
8901                    Integer.toHexString(System.identityHashCode(activity)));
8902                    out.print(' ');
8903                    activity.printComponentShortName(out);
8904            if (count > 1) {
8905                out.print(" ("); out.print(count); out.print(" filters)");
8906            }
8907            out.println();
8908        }
8909
8910//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8911//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8912//            final List<ResolveInfo> retList = Lists.newArrayList();
8913//            while (i.hasNext()) {
8914//                final ResolveInfo resolveInfo = i.next();
8915//                if (isEnabledLP(resolveInfo.activityInfo)) {
8916//                    retList.add(resolveInfo);
8917//                }
8918//            }
8919//            return retList;
8920//        }
8921
8922        // Keys are String (activity class name), values are Activity.
8923        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8924                = new ArrayMap<ComponentName, PackageParser.Activity>();
8925        private int mFlags;
8926    }
8927
8928    private final class ServiceIntentResolver
8929            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8930        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8931                boolean defaultOnly, int userId) {
8932            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8933            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8934        }
8935
8936        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8937                int userId) {
8938            if (!sUserManager.exists(userId)) return null;
8939            mFlags = flags;
8940            return super.queryIntent(intent, resolvedType,
8941                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8942        }
8943
8944        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8945                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8946            if (!sUserManager.exists(userId)) return null;
8947            if (packageServices == null) {
8948                return null;
8949            }
8950            mFlags = flags;
8951            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8952            final int N = packageServices.size();
8953            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8954                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8955
8956            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8957            for (int i = 0; i < N; ++i) {
8958                intentFilters = packageServices.get(i).intents;
8959                if (intentFilters != null && intentFilters.size() > 0) {
8960                    PackageParser.ServiceIntentInfo[] array =
8961                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8962                    intentFilters.toArray(array);
8963                    listCut.add(array);
8964                }
8965            }
8966            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8967        }
8968
8969        public final void addService(PackageParser.Service s) {
8970            mServices.put(s.getComponentName(), s);
8971            if (DEBUG_SHOW_INFO) {
8972                Log.v(TAG, "  "
8973                        + (s.info.nonLocalizedLabel != null
8974                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8975                Log.v(TAG, "    Class=" + s.info.name);
8976            }
8977            final int NI = s.intents.size();
8978            int j;
8979            for (j=0; j<NI; j++) {
8980                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8981                if (DEBUG_SHOW_INFO) {
8982                    Log.v(TAG, "    IntentFilter:");
8983                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8984                }
8985                if (!intent.debugCheck()) {
8986                    Log.w(TAG, "==> For Service " + s.info.name);
8987                }
8988                addFilter(intent);
8989            }
8990        }
8991
8992        public final void removeService(PackageParser.Service s) {
8993            mServices.remove(s.getComponentName());
8994            if (DEBUG_SHOW_INFO) {
8995                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8996                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8997                Log.v(TAG, "    Class=" + s.info.name);
8998            }
8999            final int NI = s.intents.size();
9000            int j;
9001            for (j=0; j<NI; j++) {
9002                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9003                if (DEBUG_SHOW_INFO) {
9004                    Log.v(TAG, "    IntentFilter:");
9005                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9006                }
9007                removeFilter(intent);
9008            }
9009        }
9010
9011        @Override
9012        protected boolean allowFilterResult(
9013                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9014            ServiceInfo filterSi = filter.service.info;
9015            for (int i=dest.size()-1; i>=0; i--) {
9016                ServiceInfo destAi = dest.get(i).serviceInfo;
9017                if (destAi.name == filterSi.name
9018                        && destAi.packageName == filterSi.packageName) {
9019                    return false;
9020                }
9021            }
9022            return true;
9023        }
9024
9025        @Override
9026        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9027            return new PackageParser.ServiceIntentInfo[size];
9028        }
9029
9030        @Override
9031        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9032            if (!sUserManager.exists(userId)) return true;
9033            PackageParser.Package p = filter.service.owner;
9034            if (p != null) {
9035                PackageSetting ps = (PackageSetting)p.mExtras;
9036                if (ps != null) {
9037                    // System apps are never considered stopped for purposes of
9038                    // filtering, because there may be no way for the user to
9039                    // actually re-launch them.
9040                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9041                            && ps.getStopped(userId);
9042                }
9043            }
9044            return false;
9045        }
9046
9047        @Override
9048        protected boolean isPackageForFilter(String packageName,
9049                PackageParser.ServiceIntentInfo info) {
9050            return packageName.equals(info.service.owner.packageName);
9051        }
9052
9053        @Override
9054        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9055                int match, int userId) {
9056            if (!sUserManager.exists(userId)) return null;
9057            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9058            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9059                return null;
9060            }
9061            final PackageParser.Service service = info.service;
9062            if (mSafeMode && (service.info.applicationInfo.flags
9063                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9064                return null;
9065            }
9066            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9067            if (ps == null) {
9068                return null;
9069            }
9070            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9071                    ps.readUserState(userId), userId);
9072            if (si == null) {
9073                return null;
9074            }
9075            final ResolveInfo res = new ResolveInfo();
9076            res.serviceInfo = si;
9077            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9078                res.filter = filter;
9079            }
9080            res.priority = info.getPriority();
9081            res.preferredOrder = service.owner.mPreferredOrder;
9082            res.match = match;
9083            res.isDefault = info.hasDefault;
9084            res.labelRes = info.labelRes;
9085            res.nonLocalizedLabel = info.nonLocalizedLabel;
9086            res.icon = info.icon;
9087            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9088            return res;
9089        }
9090
9091        @Override
9092        protected void sortResults(List<ResolveInfo> results) {
9093            Collections.sort(results, mResolvePrioritySorter);
9094        }
9095
9096        @Override
9097        protected void dumpFilter(PrintWriter out, String prefix,
9098                PackageParser.ServiceIntentInfo filter) {
9099            out.print(prefix); out.print(
9100                    Integer.toHexString(System.identityHashCode(filter.service)));
9101                    out.print(' ');
9102                    filter.service.printComponentShortName(out);
9103                    out.print(" filter ");
9104                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9105        }
9106
9107        @Override
9108        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9109            return filter.service;
9110        }
9111
9112        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9113            PackageParser.Service service = (PackageParser.Service)label;
9114            out.print(prefix); out.print(
9115                    Integer.toHexString(System.identityHashCode(service)));
9116                    out.print(' ');
9117                    service.printComponentShortName(out);
9118            if (count > 1) {
9119                out.print(" ("); out.print(count); out.print(" filters)");
9120            }
9121            out.println();
9122        }
9123
9124//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9125//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9126//            final List<ResolveInfo> retList = Lists.newArrayList();
9127//            while (i.hasNext()) {
9128//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9129//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9130//                    retList.add(resolveInfo);
9131//                }
9132//            }
9133//            return retList;
9134//        }
9135
9136        // Keys are String (activity class name), values are Activity.
9137        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9138                = new ArrayMap<ComponentName, PackageParser.Service>();
9139        private int mFlags;
9140    };
9141
9142    private final class ProviderIntentResolver
9143            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9144        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9145                boolean defaultOnly, int userId) {
9146            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9147            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9148        }
9149
9150        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9151                int userId) {
9152            if (!sUserManager.exists(userId))
9153                return null;
9154            mFlags = flags;
9155            return super.queryIntent(intent, resolvedType,
9156                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9157        }
9158
9159        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9160                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9161            if (!sUserManager.exists(userId))
9162                return null;
9163            if (packageProviders == null) {
9164                return null;
9165            }
9166            mFlags = flags;
9167            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9168            final int N = packageProviders.size();
9169            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9170                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9171
9172            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9173            for (int i = 0; i < N; ++i) {
9174                intentFilters = packageProviders.get(i).intents;
9175                if (intentFilters != null && intentFilters.size() > 0) {
9176                    PackageParser.ProviderIntentInfo[] array =
9177                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9178                    intentFilters.toArray(array);
9179                    listCut.add(array);
9180                }
9181            }
9182            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9183        }
9184
9185        public final void addProvider(PackageParser.Provider p) {
9186            if (mProviders.containsKey(p.getComponentName())) {
9187                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9188                return;
9189            }
9190
9191            mProviders.put(p.getComponentName(), p);
9192            if (DEBUG_SHOW_INFO) {
9193                Log.v(TAG, "  "
9194                        + (p.info.nonLocalizedLabel != null
9195                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9196                Log.v(TAG, "    Class=" + p.info.name);
9197            }
9198            final int NI = p.intents.size();
9199            int j;
9200            for (j = 0; j < NI; j++) {
9201                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9202                if (DEBUG_SHOW_INFO) {
9203                    Log.v(TAG, "    IntentFilter:");
9204                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9205                }
9206                if (!intent.debugCheck()) {
9207                    Log.w(TAG, "==> For Provider " + p.info.name);
9208                }
9209                addFilter(intent);
9210            }
9211        }
9212
9213        public final void removeProvider(PackageParser.Provider p) {
9214            mProviders.remove(p.getComponentName());
9215            if (DEBUG_SHOW_INFO) {
9216                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9217                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9218                Log.v(TAG, "    Class=" + p.info.name);
9219            }
9220            final int NI = p.intents.size();
9221            int j;
9222            for (j = 0; j < NI; j++) {
9223                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9224                if (DEBUG_SHOW_INFO) {
9225                    Log.v(TAG, "    IntentFilter:");
9226                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9227                }
9228                removeFilter(intent);
9229            }
9230        }
9231
9232        @Override
9233        protected boolean allowFilterResult(
9234                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9235            ProviderInfo filterPi = filter.provider.info;
9236            for (int i = dest.size() - 1; i >= 0; i--) {
9237                ProviderInfo destPi = dest.get(i).providerInfo;
9238                if (destPi.name == filterPi.name
9239                        && destPi.packageName == filterPi.packageName) {
9240                    return false;
9241                }
9242            }
9243            return true;
9244        }
9245
9246        @Override
9247        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9248            return new PackageParser.ProviderIntentInfo[size];
9249        }
9250
9251        @Override
9252        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9253            if (!sUserManager.exists(userId))
9254                return true;
9255            PackageParser.Package p = filter.provider.owner;
9256            if (p != null) {
9257                PackageSetting ps = (PackageSetting) p.mExtras;
9258                if (ps != null) {
9259                    // System apps are never considered stopped for purposes of
9260                    // filtering, because there may be no way for the user to
9261                    // actually re-launch them.
9262                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9263                            && ps.getStopped(userId);
9264                }
9265            }
9266            return false;
9267        }
9268
9269        @Override
9270        protected boolean isPackageForFilter(String packageName,
9271                PackageParser.ProviderIntentInfo info) {
9272            return packageName.equals(info.provider.owner.packageName);
9273        }
9274
9275        @Override
9276        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9277                int match, int userId) {
9278            if (!sUserManager.exists(userId))
9279                return null;
9280            final PackageParser.ProviderIntentInfo info = filter;
9281            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9282                return null;
9283            }
9284            final PackageParser.Provider provider = info.provider;
9285            if (mSafeMode && (provider.info.applicationInfo.flags
9286                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9287                return null;
9288            }
9289            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9290            if (ps == null) {
9291                return null;
9292            }
9293            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9294                    ps.readUserState(userId), userId);
9295            if (pi == null) {
9296                return null;
9297            }
9298            final ResolveInfo res = new ResolveInfo();
9299            res.providerInfo = pi;
9300            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9301                res.filter = filter;
9302            }
9303            res.priority = info.getPriority();
9304            res.preferredOrder = provider.owner.mPreferredOrder;
9305            res.match = match;
9306            res.isDefault = info.hasDefault;
9307            res.labelRes = info.labelRes;
9308            res.nonLocalizedLabel = info.nonLocalizedLabel;
9309            res.icon = info.icon;
9310            res.system = res.providerInfo.applicationInfo.isSystemApp();
9311            return res;
9312        }
9313
9314        @Override
9315        protected void sortResults(List<ResolveInfo> results) {
9316            Collections.sort(results, mResolvePrioritySorter);
9317        }
9318
9319        @Override
9320        protected void dumpFilter(PrintWriter out, String prefix,
9321                PackageParser.ProviderIntentInfo filter) {
9322            out.print(prefix);
9323            out.print(
9324                    Integer.toHexString(System.identityHashCode(filter.provider)));
9325            out.print(' ');
9326            filter.provider.printComponentShortName(out);
9327            out.print(" filter ");
9328            out.println(Integer.toHexString(System.identityHashCode(filter)));
9329        }
9330
9331        @Override
9332        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9333            return filter.provider;
9334        }
9335
9336        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9337            PackageParser.Provider provider = (PackageParser.Provider)label;
9338            out.print(prefix); out.print(
9339                    Integer.toHexString(System.identityHashCode(provider)));
9340                    out.print(' ');
9341                    provider.printComponentShortName(out);
9342            if (count > 1) {
9343                out.print(" ("); out.print(count); out.print(" filters)");
9344            }
9345            out.println();
9346        }
9347
9348        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9349                = new ArrayMap<ComponentName, PackageParser.Provider>();
9350        private int mFlags;
9351    };
9352
9353    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9354            new Comparator<ResolveInfo>() {
9355        public int compare(ResolveInfo r1, ResolveInfo r2) {
9356            int v1 = r1.priority;
9357            int v2 = r2.priority;
9358            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9359            if (v1 != v2) {
9360                return (v1 > v2) ? -1 : 1;
9361            }
9362            v1 = r1.preferredOrder;
9363            v2 = r2.preferredOrder;
9364            if (v1 != v2) {
9365                return (v1 > v2) ? -1 : 1;
9366            }
9367            if (r1.isDefault != r2.isDefault) {
9368                return r1.isDefault ? -1 : 1;
9369            }
9370            v1 = r1.match;
9371            v2 = r2.match;
9372            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9373            if (v1 != v2) {
9374                return (v1 > v2) ? -1 : 1;
9375            }
9376            if (r1.system != r2.system) {
9377                return r1.system ? -1 : 1;
9378            }
9379            return 0;
9380        }
9381    };
9382
9383    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9384            new Comparator<ProviderInfo>() {
9385        public int compare(ProviderInfo p1, ProviderInfo p2) {
9386            final int v1 = p1.initOrder;
9387            final int v2 = p2.initOrder;
9388            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9389        }
9390    };
9391
9392    final void sendPackageBroadcast(final String action, final String pkg,
9393            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9394            final int[] userIds) {
9395        mHandler.post(new Runnable() {
9396            @Override
9397            public void run() {
9398                try {
9399                    final IActivityManager am = ActivityManagerNative.getDefault();
9400                    if (am == null) return;
9401                    final int[] resolvedUserIds;
9402                    if (userIds == null) {
9403                        resolvedUserIds = am.getRunningUserIds();
9404                    } else {
9405                        resolvedUserIds = userIds;
9406                    }
9407                    for (int id : resolvedUserIds) {
9408                        final Intent intent = new Intent(action,
9409                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9410                        if (extras != null) {
9411                            intent.putExtras(extras);
9412                        }
9413                        if (targetPkg != null) {
9414                            intent.setPackage(targetPkg);
9415                        }
9416                        // Modify the UID when posting to other users
9417                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9418                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9419                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9420                            intent.putExtra(Intent.EXTRA_UID, uid);
9421                        }
9422                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9423                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9424                        if (DEBUG_BROADCASTS) {
9425                            RuntimeException here = new RuntimeException("here");
9426                            here.fillInStackTrace();
9427                            Slog.d(TAG, "Sending to user " + id + ": "
9428                                    + intent.toShortString(false, true, false, false)
9429                                    + " " + intent.getExtras(), here);
9430                        }
9431                        am.broadcastIntent(null, intent, null, finishedReceiver,
9432                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9433                                null, finishedReceiver != null, false, id);
9434                    }
9435                } catch (RemoteException ex) {
9436                }
9437            }
9438        });
9439    }
9440
9441    /**
9442     * Check if the external storage media is available. This is true if there
9443     * is a mounted external storage medium or if the external storage is
9444     * emulated.
9445     */
9446    private boolean isExternalMediaAvailable() {
9447        return mMediaMounted || Environment.isExternalStorageEmulated();
9448    }
9449
9450    @Override
9451    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9452        // writer
9453        synchronized (mPackages) {
9454            if (!isExternalMediaAvailable()) {
9455                // If the external storage is no longer mounted at this point,
9456                // the caller may not have been able to delete all of this
9457                // packages files and can not delete any more.  Bail.
9458                return null;
9459            }
9460            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9461            if (lastPackage != null) {
9462                pkgs.remove(lastPackage);
9463            }
9464            if (pkgs.size() > 0) {
9465                return pkgs.get(0);
9466            }
9467        }
9468        return null;
9469    }
9470
9471    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9472        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9473                userId, andCode ? 1 : 0, packageName);
9474        if (mSystemReady) {
9475            msg.sendToTarget();
9476        } else {
9477            if (mPostSystemReadyMessages == null) {
9478                mPostSystemReadyMessages = new ArrayList<>();
9479            }
9480            mPostSystemReadyMessages.add(msg);
9481        }
9482    }
9483
9484    void startCleaningPackages() {
9485        // reader
9486        synchronized (mPackages) {
9487            if (!isExternalMediaAvailable()) {
9488                return;
9489            }
9490            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9491                return;
9492            }
9493        }
9494        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9495        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9496        IActivityManager am = ActivityManagerNative.getDefault();
9497        if (am != null) {
9498            try {
9499                am.startService(null, intent, null, mContext.getOpPackageName(),
9500                        UserHandle.USER_OWNER);
9501            } catch (RemoteException e) {
9502            }
9503        }
9504    }
9505
9506    @Override
9507    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9508            int installFlags, String installerPackageName, VerificationParams verificationParams,
9509            String packageAbiOverride) {
9510        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9511                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9512    }
9513
9514    @Override
9515    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9516            int installFlags, String installerPackageName, VerificationParams verificationParams,
9517            String packageAbiOverride, int userId) {
9518        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9519
9520        final int callingUid = Binder.getCallingUid();
9521        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9522
9523        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9524            try {
9525                if (observer != null) {
9526                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9527                }
9528            } catch (RemoteException re) {
9529            }
9530            return;
9531        }
9532
9533        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9534            installFlags |= PackageManager.INSTALL_FROM_ADB;
9535
9536        } else {
9537            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9538            // about installerPackageName.
9539
9540            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9541            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9542        }
9543
9544        UserHandle user;
9545        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9546            user = UserHandle.ALL;
9547        } else {
9548            user = new UserHandle(userId);
9549        }
9550
9551        // Only system components can circumvent runtime permissions when installing.
9552        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9553                && mContext.checkCallingOrSelfPermission(Manifest.permission
9554                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9555            throw new SecurityException("You need the "
9556                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9557                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9558        }
9559
9560        verificationParams.setInstallerUid(callingUid);
9561
9562        final File originFile = new File(originPath);
9563        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9564
9565        final Message msg = mHandler.obtainMessage(INIT_COPY);
9566        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9567                null, verificationParams, user, packageAbiOverride, null);
9568        mHandler.sendMessage(msg);
9569    }
9570
9571    void installStage(String packageName, File stagedDir, String stagedCid,
9572            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9573            String installerPackageName, int installerUid, UserHandle user) {
9574        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9575                params.referrerUri, installerUid, null);
9576        verifParams.setInstallerUid(installerUid);
9577
9578        final OriginInfo origin;
9579        if (stagedDir != null) {
9580            origin = OriginInfo.fromStagedFile(stagedDir);
9581        } else {
9582            origin = OriginInfo.fromStagedContainer(stagedCid);
9583        }
9584
9585        final Message msg = mHandler.obtainMessage(INIT_COPY);
9586        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9587                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9588                params.grantedRuntimePermissions);
9589        mHandler.sendMessage(msg);
9590    }
9591
9592    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9593        Bundle extras = new Bundle(1);
9594        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9595
9596        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9597                packageName, extras, null, null, new int[] {userId});
9598        try {
9599            IActivityManager am = ActivityManagerNative.getDefault();
9600            final boolean isSystem =
9601                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9602            if (isSystem && am.isUserRunning(userId, false)) {
9603                // The just-installed/enabled app is bundled on the system, so presumed
9604                // to be able to run automatically without needing an explicit launch.
9605                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9606                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9607                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9608                        .setPackage(packageName);
9609                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9610                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9611            }
9612        } catch (RemoteException e) {
9613            // shouldn't happen
9614            Slog.w(TAG, "Unable to bootstrap installed package", e);
9615        }
9616    }
9617
9618    @Override
9619    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9620            int userId) {
9621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9622        PackageSetting pkgSetting;
9623        final int uid = Binder.getCallingUid();
9624        enforceCrossUserPermission(uid, userId, true, true,
9625                "setApplicationHiddenSetting for user " + userId);
9626
9627        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9628            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9629            return false;
9630        }
9631
9632        long callingId = Binder.clearCallingIdentity();
9633        try {
9634            boolean sendAdded = false;
9635            boolean sendRemoved = false;
9636            // writer
9637            synchronized (mPackages) {
9638                pkgSetting = mSettings.mPackages.get(packageName);
9639                if (pkgSetting == null) {
9640                    return false;
9641                }
9642                if (pkgSetting.getHidden(userId) != hidden) {
9643                    pkgSetting.setHidden(hidden, userId);
9644                    mSettings.writePackageRestrictionsLPr(userId);
9645                    if (hidden) {
9646                        sendRemoved = true;
9647                    } else {
9648                        sendAdded = true;
9649                    }
9650                }
9651            }
9652            if (sendAdded) {
9653                sendPackageAddedForUser(packageName, pkgSetting, userId);
9654                return true;
9655            }
9656            if (sendRemoved) {
9657                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9658                        "hiding pkg");
9659                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9660                return true;
9661            }
9662        } finally {
9663            Binder.restoreCallingIdentity(callingId);
9664        }
9665        return false;
9666    }
9667
9668    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9669            int userId) {
9670        final PackageRemovedInfo info = new PackageRemovedInfo();
9671        info.removedPackage = packageName;
9672        info.removedUsers = new int[] {userId};
9673        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9674        info.sendBroadcast(false, false, false);
9675    }
9676
9677    /**
9678     * Returns true if application is not found or there was an error. Otherwise it returns
9679     * the hidden state of the package for the given user.
9680     */
9681    @Override
9682    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9683        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9684        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9685                false, "getApplicationHidden for user " + userId);
9686        PackageSetting pkgSetting;
9687        long callingId = Binder.clearCallingIdentity();
9688        try {
9689            // writer
9690            synchronized (mPackages) {
9691                pkgSetting = mSettings.mPackages.get(packageName);
9692                if (pkgSetting == null) {
9693                    return true;
9694                }
9695                return pkgSetting.getHidden(userId);
9696            }
9697        } finally {
9698            Binder.restoreCallingIdentity(callingId);
9699        }
9700    }
9701
9702    /**
9703     * @hide
9704     */
9705    @Override
9706    public int installExistingPackageAsUser(String packageName, int userId) {
9707        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9708                null);
9709        PackageSetting pkgSetting;
9710        final int uid = Binder.getCallingUid();
9711        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9712                + userId);
9713        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9714            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9715        }
9716
9717        long callingId = Binder.clearCallingIdentity();
9718        try {
9719            boolean sendAdded = false;
9720
9721            // writer
9722            synchronized (mPackages) {
9723                pkgSetting = mSettings.mPackages.get(packageName);
9724                if (pkgSetting == null) {
9725                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9726                }
9727                if (!pkgSetting.getInstalled(userId)) {
9728                    pkgSetting.setInstalled(true, userId);
9729                    pkgSetting.setHidden(false, userId);
9730                    mSettings.writePackageRestrictionsLPr(userId);
9731                    sendAdded = true;
9732                }
9733            }
9734
9735            if (sendAdded) {
9736                sendPackageAddedForUser(packageName, pkgSetting, userId);
9737            }
9738        } finally {
9739            Binder.restoreCallingIdentity(callingId);
9740        }
9741
9742        return PackageManager.INSTALL_SUCCEEDED;
9743    }
9744
9745    boolean isUserRestricted(int userId, String restrictionKey) {
9746        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9747        if (restrictions.getBoolean(restrictionKey, false)) {
9748            Log.w(TAG, "User is restricted: " + restrictionKey);
9749            return true;
9750        }
9751        return false;
9752    }
9753
9754    @Override
9755    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9756        mContext.enforceCallingOrSelfPermission(
9757                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9758                "Only package verification agents can verify applications");
9759
9760        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9761        final PackageVerificationResponse response = new PackageVerificationResponse(
9762                verificationCode, Binder.getCallingUid());
9763        msg.arg1 = id;
9764        msg.obj = response;
9765        mHandler.sendMessage(msg);
9766    }
9767
9768    @Override
9769    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9770            long millisecondsToDelay) {
9771        mContext.enforceCallingOrSelfPermission(
9772                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9773                "Only package verification agents can extend verification timeouts");
9774
9775        final PackageVerificationState state = mPendingVerification.get(id);
9776        final PackageVerificationResponse response = new PackageVerificationResponse(
9777                verificationCodeAtTimeout, Binder.getCallingUid());
9778
9779        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9780            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9781        }
9782        if (millisecondsToDelay < 0) {
9783            millisecondsToDelay = 0;
9784        }
9785        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9786                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9787            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9788        }
9789
9790        if ((state != null) && !state.timeoutExtended()) {
9791            state.extendTimeout();
9792
9793            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9794            msg.arg1 = id;
9795            msg.obj = response;
9796            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9797        }
9798    }
9799
9800    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9801            int verificationCode, UserHandle user) {
9802        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9803        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9804        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9805        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9806        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9807
9808        mContext.sendBroadcastAsUser(intent, user,
9809                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9810    }
9811
9812    private ComponentName matchComponentForVerifier(String packageName,
9813            List<ResolveInfo> receivers) {
9814        ActivityInfo targetReceiver = null;
9815
9816        final int NR = receivers.size();
9817        for (int i = 0; i < NR; i++) {
9818            final ResolveInfo info = receivers.get(i);
9819            if (info.activityInfo == null) {
9820                continue;
9821            }
9822
9823            if (packageName.equals(info.activityInfo.packageName)) {
9824                targetReceiver = info.activityInfo;
9825                break;
9826            }
9827        }
9828
9829        if (targetReceiver == null) {
9830            return null;
9831        }
9832
9833        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9834    }
9835
9836    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9837            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9838        if (pkgInfo.verifiers.length == 0) {
9839            return null;
9840        }
9841
9842        final int N = pkgInfo.verifiers.length;
9843        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9844        for (int i = 0; i < N; i++) {
9845            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9846
9847            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9848                    receivers);
9849            if (comp == null) {
9850                continue;
9851            }
9852
9853            final int verifierUid = getUidForVerifier(verifierInfo);
9854            if (verifierUid == -1) {
9855                continue;
9856            }
9857
9858            if (DEBUG_VERIFY) {
9859                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9860                        + " with the correct signature");
9861            }
9862            sufficientVerifiers.add(comp);
9863            verificationState.addSufficientVerifier(verifierUid);
9864        }
9865
9866        return sufficientVerifiers;
9867    }
9868
9869    private int getUidForVerifier(VerifierInfo verifierInfo) {
9870        synchronized (mPackages) {
9871            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9872            if (pkg == null) {
9873                return -1;
9874            } else if (pkg.mSignatures.length != 1) {
9875                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9876                        + " has more than one signature; ignoring");
9877                return -1;
9878            }
9879
9880            /*
9881             * If the public key of the package's signature does not match
9882             * our expected public key, then this is a different package and
9883             * we should skip.
9884             */
9885
9886            final byte[] expectedPublicKey;
9887            try {
9888                final Signature verifierSig = pkg.mSignatures[0];
9889                final PublicKey publicKey = verifierSig.getPublicKey();
9890                expectedPublicKey = publicKey.getEncoded();
9891            } catch (CertificateException e) {
9892                return -1;
9893            }
9894
9895            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9896
9897            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9898                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9899                        + " does not have the expected public key; ignoring");
9900                return -1;
9901            }
9902
9903            return pkg.applicationInfo.uid;
9904        }
9905    }
9906
9907    @Override
9908    public void finishPackageInstall(int token) {
9909        enforceSystemOrRoot("Only the system is allowed to finish installs");
9910
9911        if (DEBUG_INSTALL) {
9912            Slog.v(TAG, "BM finishing package install for " + token);
9913        }
9914
9915        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9916        mHandler.sendMessage(msg);
9917    }
9918
9919    /**
9920     * Get the verification agent timeout.
9921     *
9922     * @return verification timeout in milliseconds
9923     */
9924    private long getVerificationTimeout() {
9925        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9926                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9927                DEFAULT_VERIFICATION_TIMEOUT);
9928    }
9929
9930    /**
9931     * Get the default verification agent response code.
9932     *
9933     * @return default verification response code
9934     */
9935    private int getDefaultVerificationResponse() {
9936        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9937                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9938                DEFAULT_VERIFICATION_RESPONSE);
9939    }
9940
9941    /**
9942     * Check whether or not package verification has been enabled.
9943     *
9944     * @return true if verification should be performed
9945     */
9946    private boolean isVerificationEnabled(int userId, int installFlags) {
9947        if (!DEFAULT_VERIFY_ENABLE) {
9948            return false;
9949        }
9950
9951        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9952
9953        // Check if installing from ADB
9954        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9955            // Do not run verification in a test harness environment
9956            if (ActivityManager.isRunningInTestHarness()) {
9957                return false;
9958            }
9959            if (ensureVerifyAppsEnabled) {
9960                return true;
9961            }
9962            // Check if the developer does not want package verification for ADB installs
9963            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9964                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9965                return false;
9966            }
9967        }
9968
9969        if (ensureVerifyAppsEnabled) {
9970            return true;
9971        }
9972
9973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9974                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9975    }
9976
9977    @Override
9978    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9979            throws RemoteException {
9980        mContext.enforceCallingOrSelfPermission(
9981                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9982                "Only intentfilter verification agents can verify applications");
9983
9984        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9985        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9986                Binder.getCallingUid(), verificationCode, failedDomains);
9987        msg.arg1 = id;
9988        msg.obj = response;
9989        mHandler.sendMessage(msg);
9990    }
9991
9992    @Override
9993    public int getIntentVerificationStatus(String packageName, int userId) {
9994        synchronized (mPackages) {
9995            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9996        }
9997    }
9998
9999    @Override
10000    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10001        mContext.enforceCallingOrSelfPermission(
10002                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10003
10004        boolean result = false;
10005        synchronized (mPackages) {
10006            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10007        }
10008        if (result) {
10009            scheduleWritePackageRestrictionsLocked(userId);
10010        }
10011        return result;
10012    }
10013
10014    @Override
10015    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10016        synchronized (mPackages) {
10017            return mSettings.getIntentFilterVerificationsLPr(packageName);
10018        }
10019    }
10020
10021    @Override
10022    public List<IntentFilter> getAllIntentFilters(String packageName) {
10023        if (TextUtils.isEmpty(packageName)) {
10024            return Collections.<IntentFilter>emptyList();
10025        }
10026        synchronized (mPackages) {
10027            PackageParser.Package pkg = mPackages.get(packageName);
10028            if (pkg == null || pkg.activities == null) {
10029                return Collections.<IntentFilter>emptyList();
10030            }
10031            final int count = pkg.activities.size();
10032            ArrayList<IntentFilter> result = new ArrayList<>();
10033            for (int n=0; n<count; n++) {
10034                PackageParser.Activity activity = pkg.activities.get(n);
10035                if (activity.intents != null || activity.intents.size() > 0) {
10036                    result.addAll(activity.intents);
10037                }
10038            }
10039            return result;
10040        }
10041    }
10042
10043    @Override
10044    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10045        mContext.enforceCallingOrSelfPermission(
10046                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10047
10048        synchronized (mPackages) {
10049            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10050            if (packageName != null) {
10051                result |= updateIntentVerificationStatus(packageName,
10052                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10053                        userId);
10054                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10055                        packageName, userId);
10056            }
10057            return result;
10058        }
10059    }
10060
10061    @Override
10062    public String getDefaultBrowserPackageName(int userId) {
10063        synchronized (mPackages) {
10064            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10065        }
10066    }
10067
10068    /**
10069     * Get the "allow unknown sources" setting.
10070     *
10071     * @return the current "allow unknown sources" setting
10072     */
10073    private int getUnknownSourcesSettings() {
10074        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10075                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10076                -1);
10077    }
10078
10079    @Override
10080    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10081        final int uid = Binder.getCallingUid();
10082        // writer
10083        synchronized (mPackages) {
10084            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10085            if (targetPackageSetting == null) {
10086                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10087            }
10088
10089            PackageSetting installerPackageSetting;
10090            if (installerPackageName != null) {
10091                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10092                if (installerPackageSetting == null) {
10093                    throw new IllegalArgumentException("Unknown installer package: "
10094                            + installerPackageName);
10095                }
10096            } else {
10097                installerPackageSetting = null;
10098            }
10099
10100            Signature[] callerSignature;
10101            Object obj = mSettings.getUserIdLPr(uid);
10102            if (obj != null) {
10103                if (obj instanceof SharedUserSetting) {
10104                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10105                } else if (obj instanceof PackageSetting) {
10106                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10107                } else {
10108                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10109                }
10110            } else {
10111                throw new SecurityException("Unknown calling uid " + uid);
10112            }
10113
10114            // Verify: can't set installerPackageName to a package that is
10115            // not signed with the same cert as the caller.
10116            if (installerPackageSetting != null) {
10117                if (compareSignatures(callerSignature,
10118                        installerPackageSetting.signatures.mSignatures)
10119                        != PackageManager.SIGNATURE_MATCH) {
10120                    throw new SecurityException(
10121                            "Caller does not have same cert as new installer package "
10122                            + installerPackageName);
10123                }
10124            }
10125
10126            // Verify: if target already has an installer package, it must
10127            // be signed with the same cert as the caller.
10128            if (targetPackageSetting.installerPackageName != null) {
10129                PackageSetting setting = mSettings.mPackages.get(
10130                        targetPackageSetting.installerPackageName);
10131                // If the currently set package isn't valid, then it's always
10132                // okay to change it.
10133                if (setting != null) {
10134                    if (compareSignatures(callerSignature,
10135                            setting.signatures.mSignatures)
10136                            != PackageManager.SIGNATURE_MATCH) {
10137                        throw new SecurityException(
10138                                "Caller does not have same cert as old installer package "
10139                                + targetPackageSetting.installerPackageName);
10140                    }
10141                }
10142            }
10143
10144            // Okay!
10145            targetPackageSetting.installerPackageName = installerPackageName;
10146            scheduleWriteSettingsLocked();
10147        }
10148    }
10149
10150    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10151        // Queue up an async operation since the package installation may take a little while.
10152        mHandler.post(new Runnable() {
10153            public void run() {
10154                mHandler.removeCallbacks(this);
10155                 // Result object to be returned
10156                PackageInstalledInfo res = new PackageInstalledInfo();
10157                res.returnCode = currentStatus;
10158                res.uid = -1;
10159                res.pkg = null;
10160                res.removedInfo = new PackageRemovedInfo();
10161                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10162                    args.doPreInstall(res.returnCode);
10163                    synchronized (mInstallLock) {
10164                        installPackageLI(args, res);
10165                    }
10166                    args.doPostInstall(res.returnCode, res.uid);
10167                }
10168
10169                // A restore should be performed at this point if (a) the install
10170                // succeeded, (b) the operation is not an update, and (c) the new
10171                // package has not opted out of backup participation.
10172                final boolean update = res.removedInfo.removedPackage != null;
10173                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10174                boolean doRestore = !update
10175                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10176
10177                // Set up the post-install work request bookkeeping.  This will be used
10178                // and cleaned up by the post-install event handling regardless of whether
10179                // there's a restore pass performed.  Token values are >= 1.
10180                int token;
10181                if (mNextInstallToken < 0) mNextInstallToken = 1;
10182                token = mNextInstallToken++;
10183
10184                PostInstallData data = new PostInstallData(args, res);
10185                mRunningInstalls.put(token, data);
10186                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10187
10188                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10189                    // Pass responsibility to the Backup Manager.  It will perform a
10190                    // restore if appropriate, then pass responsibility back to the
10191                    // Package Manager to run the post-install observer callbacks
10192                    // and broadcasts.
10193                    IBackupManager bm = IBackupManager.Stub.asInterface(
10194                            ServiceManager.getService(Context.BACKUP_SERVICE));
10195                    if (bm != null) {
10196                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10197                                + " to BM for possible restore");
10198                        try {
10199                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10200                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10201                            } else {
10202                                doRestore = false;
10203                            }
10204                        } catch (RemoteException e) {
10205                            // can't happen; the backup manager is local
10206                        } catch (Exception e) {
10207                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10208                            doRestore = false;
10209                        }
10210                    } else {
10211                        Slog.e(TAG, "Backup Manager not found!");
10212                        doRestore = false;
10213                    }
10214                }
10215
10216                if (!doRestore) {
10217                    // No restore possible, or the Backup Manager was mysteriously not
10218                    // available -- just fire the post-install work request directly.
10219                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10220                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10221                    mHandler.sendMessage(msg);
10222                }
10223            }
10224        });
10225    }
10226
10227    private abstract class HandlerParams {
10228        private static final int MAX_RETRIES = 4;
10229
10230        /**
10231         * Number of times startCopy() has been attempted and had a non-fatal
10232         * error.
10233         */
10234        private int mRetries = 0;
10235
10236        /** User handle for the user requesting the information or installation. */
10237        private final UserHandle mUser;
10238
10239        HandlerParams(UserHandle user) {
10240            mUser = user;
10241        }
10242
10243        UserHandle getUser() {
10244            return mUser;
10245        }
10246
10247        final boolean startCopy() {
10248            boolean res;
10249            try {
10250                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10251
10252                if (++mRetries > MAX_RETRIES) {
10253                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10254                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10255                    handleServiceError();
10256                    return false;
10257                } else {
10258                    handleStartCopy();
10259                    res = true;
10260                }
10261            } catch (RemoteException e) {
10262                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10263                mHandler.sendEmptyMessage(MCS_RECONNECT);
10264                res = false;
10265            }
10266            handleReturnCode();
10267            return res;
10268        }
10269
10270        final void serviceError() {
10271            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10272            handleServiceError();
10273            handleReturnCode();
10274        }
10275
10276        abstract void handleStartCopy() throws RemoteException;
10277        abstract void handleServiceError();
10278        abstract void handleReturnCode();
10279    }
10280
10281    class MeasureParams extends HandlerParams {
10282        private final PackageStats mStats;
10283        private boolean mSuccess;
10284
10285        private final IPackageStatsObserver mObserver;
10286
10287        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10288            super(new UserHandle(stats.userHandle));
10289            mObserver = observer;
10290            mStats = stats;
10291        }
10292
10293        @Override
10294        public String toString() {
10295            return "MeasureParams{"
10296                + Integer.toHexString(System.identityHashCode(this))
10297                + " " + mStats.packageName + "}";
10298        }
10299
10300        @Override
10301        void handleStartCopy() throws RemoteException {
10302            synchronized (mInstallLock) {
10303                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10304            }
10305
10306            if (mSuccess) {
10307                final boolean mounted;
10308                if (Environment.isExternalStorageEmulated()) {
10309                    mounted = true;
10310                } else {
10311                    final String status = Environment.getExternalStorageState();
10312                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10313                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10314                }
10315
10316                if (mounted) {
10317                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10318
10319                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10320                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10321
10322                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10323                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10324
10325                    // Always subtract cache size, since it's a subdirectory
10326                    mStats.externalDataSize -= mStats.externalCacheSize;
10327
10328                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10329                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10330
10331                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10332                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10333                }
10334            }
10335        }
10336
10337        @Override
10338        void handleReturnCode() {
10339            if (mObserver != null) {
10340                try {
10341                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10342                } catch (RemoteException e) {
10343                    Slog.i(TAG, "Observer no longer exists.");
10344                }
10345            }
10346        }
10347
10348        @Override
10349        void handleServiceError() {
10350            Slog.e(TAG, "Could not measure application " + mStats.packageName
10351                            + " external storage");
10352        }
10353    }
10354
10355    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10356            throws RemoteException {
10357        long result = 0;
10358        for (File path : paths) {
10359            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10360        }
10361        return result;
10362    }
10363
10364    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10365        for (File path : paths) {
10366            try {
10367                mcs.clearDirectory(path.getAbsolutePath());
10368            } catch (RemoteException e) {
10369            }
10370        }
10371    }
10372
10373    static class OriginInfo {
10374        /**
10375         * Location where install is coming from, before it has been
10376         * copied/renamed into place. This could be a single monolithic APK
10377         * file, or a cluster directory. This location may be untrusted.
10378         */
10379        final File file;
10380        final String cid;
10381
10382        /**
10383         * Flag indicating that {@link #file} or {@link #cid} has already been
10384         * staged, meaning downstream users don't need to defensively copy the
10385         * contents.
10386         */
10387        final boolean staged;
10388
10389        /**
10390         * Flag indicating that {@link #file} or {@link #cid} is an already
10391         * installed app that is being moved.
10392         */
10393        final boolean existing;
10394
10395        final String resolvedPath;
10396        final File resolvedFile;
10397
10398        static OriginInfo fromNothing() {
10399            return new OriginInfo(null, null, false, false);
10400        }
10401
10402        static OriginInfo fromUntrustedFile(File file) {
10403            return new OriginInfo(file, null, false, false);
10404        }
10405
10406        static OriginInfo fromExistingFile(File file) {
10407            return new OriginInfo(file, null, false, true);
10408        }
10409
10410        static OriginInfo fromStagedFile(File file) {
10411            return new OriginInfo(file, null, true, false);
10412        }
10413
10414        static OriginInfo fromStagedContainer(String cid) {
10415            return new OriginInfo(null, cid, true, false);
10416        }
10417
10418        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10419            this.file = file;
10420            this.cid = cid;
10421            this.staged = staged;
10422            this.existing = existing;
10423
10424            if (cid != null) {
10425                resolvedPath = PackageHelper.getSdDir(cid);
10426                resolvedFile = new File(resolvedPath);
10427            } else if (file != null) {
10428                resolvedPath = file.getAbsolutePath();
10429                resolvedFile = file;
10430            } else {
10431                resolvedPath = null;
10432                resolvedFile = null;
10433            }
10434        }
10435    }
10436
10437    class MoveInfo {
10438        final int moveId;
10439        final String fromUuid;
10440        final String toUuid;
10441        final String packageName;
10442        final String dataAppName;
10443        final int appId;
10444        final String seinfo;
10445
10446        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10447                String dataAppName, int appId, String seinfo) {
10448            this.moveId = moveId;
10449            this.fromUuid = fromUuid;
10450            this.toUuid = toUuid;
10451            this.packageName = packageName;
10452            this.dataAppName = dataAppName;
10453            this.appId = appId;
10454            this.seinfo = seinfo;
10455        }
10456    }
10457
10458    class InstallParams extends HandlerParams {
10459        final OriginInfo origin;
10460        final MoveInfo move;
10461        final IPackageInstallObserver2 observer;
10462        int installFlags;
10463        final String installerPackageName;
10464        final String volumeUuid;
10465        final VerificationParams verificationParams;
10466        private InstallArgs mArgs;
10467        private int mRet;
10468        final String packageAbiOverride;
10469        final String[] grantedRuntimePermissions;
10470
10471
10472        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10473                int installFlags, String installerPackageName, String volumeUuid,
10474                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10475                String[] grantedPermissions) {
10476            super(user);
10477            this.origin = origin;
10478            this.move = move;
10479            this.observer = observer;
10480            this.installFlags = installFlags;
10481            this.installerPackageName = installerPackageName;
10482            this.volumeUuid = volumeUuid;
10483            this.verificationParams = verificationParams;
10484            this.packageAbiOverride = packageAbiOverride;
10485            this.grantedRuntimePermissions = grantedPermissions;
10486        }
10487
10488        @Override
10489        public String toString() {
10490            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10491                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10492        }
10493
10494        public ManifestDigest getManifestDigest() {
10495            if (verificationParams == null) {
10496                return null;
10497            }
10498            return verificationParams.getManifestDigest();
10499        }
10500
10501        private int installLocationPolicy(PackageInfoLite pkgLite) {
10502            String packageName = pkgLite.packageName;
10503            int installLocation = pkgLite.installLocation;
10504            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10505            // reader
10506            synchronized (mPackages) {
10507                PackageParser.Package pkg = mPackages.get(packageName);
10508                if (pkg != null) {
10509                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10510                        // Check for downgrading.
10511                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10512                            try {
10513                                checkDowngrade(pkg, pkgLite);
10514                            } catch (PackageManagerException e) {
10515                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10516                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10517                            }
10518                        }
10519                        // Check for updated system application.
10520                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10521                            if (onSd) {
10522                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10523                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10524                            }
10525                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10526                        } else {
10527                            if (onSd) {
10528                                // Install flag overrides everything.
10529                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10530                            }
10531                            // If current upgrade specifies particular preference
10532                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10533                                // Application explicitly specified internal.
10534                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10535                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10536                                // App explictly prefers external. Let policy decide
10537                            } else {
10538                                // Prefer previous location
10539                                if (isExternal(pkg)) {
10540                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10541                                }
10542                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10543                            }
10544                        }
10545                    } else {
10546                        // Invalid install. Return error code
10547                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10548                    }
10549                }
10550            }
10551            // All the special cases have been taken care of.
10552            // Return result based on recommended install location.
10553            if (onSd) {
10554                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10555            }
10556            return pkgLite.recommendedInstallLocation;
10557        }
10558
10559        /*
10560         * Invoke remote method to get package information and install
10561         * location values. Override install location based on default
10562         * policy if needed and then create install arguments based
10563         * on the install location.
10564         */
10565        public void handleStartCopy() throws RemoteException {
10566            int ret = PackageManager.INSTALL_SUCCEEDED;
10567
10568            // If we're already staged, we've firmly committed to an install location
10569            if (origin.staged) {
10570                if (origin.file != null) {
10571                    installFlags |= PackageManager.INSTALL_INTERNAL;
10572                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10573                } else if (origin.cid != null) {
10574                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10575                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10576                } else {
10577                    throw new IllegalStateException("Invalid stage location");
10578                }
10579            }
10580
10581            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10582            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10583
10584            PackageInfoLite pkgLite = null;
10585
10586            if (onInt && onSd) {
10587                // Check if both bits are set.
10588                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10589                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10590            } else {
10591                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10592                        packageAbiOverride);
10593
10594                /*
10595                 * If we have too little free space, try to free cache
10596                 * before giving up.
10597                 */
10598                if (!origin.staged && pkgLite.recommendedInstallLocation
10599                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10600                    // TODO: focus freeing disk space on the target device
10601                    final StorageManager storage = StorageManager.from(mContext);
10602                    final long lowThreshold = storage.getStorageLowBytes(
10603                            Environment.getDataDirectory());
10604
10605                    final long sizeBytes = mContainerService.calculateInstalledSize(
10606                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10607
10608                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10609                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10610                                installFlags, packageAbiOverride);
10611                    }
10612
10613                    /*
10614                     * The cache free must have deleted the file we
10615                     * downloaded to install.
10616                     *
10617                     * TODO: fix the "freeCache" call to not delete
10618                     *       the file we care about.
10619                     */
10620                    if (pkgLite.recommendedInstallLocation
10621                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10622                        pkgLite.recommendedInstallLocation
10623                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10624                    }
10625                }
10626            }
10627
10628            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10629                int loc = pkgLite.recommendedInstallLocation;
10630                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10631                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10632                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10633                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10634                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10635                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10636                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10637                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10638                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10639                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10640                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10641                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10642                } else {
10643                    // Override with defaults if needed.
10644                    loc = installLocationPolicy(pkgLite);
10645                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10646                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10647                    } else if (!onSd && !onInt) {
10648                        // Override install location with flags
10649                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10650                            // Set the flag to install on external media.
10651                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10652                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10653                        } else {
10654                            // Make sure the flag for installing on external
10655                            // media is unset
10656                            installFlags |= PackageManager.INSTALL_INTERNAL;
10657                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10658                        }
10659                    }
10660                }
10661            }
10662
10663            final InstallArgs args = createInstallArgs(this);
10664            mArgs = args;
10665
10666            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10667                 /*
10668                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10669                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10670                 */
10671                int userIdentifier = getUser().getIdentifier();
10672                if (userIdentifier == UserHandle.USER_ALL
10673                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10674                    userIdentifier = UserHandle.USER_OWNER;
10675                }
10676
10677                /*
10678                 * Determine if we have any installed package verifiers. If we
10679                 * do, then we'll defer to them to verify the packages.
10680                 */
10681                final int requiredUid = mRequiredVerifierPackage == null ? -1
10682                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10683                if (!origin.existing && requiredUid != -1
10684                        && isVerificationEnabled(userIdentifier, installFlags)) {
10685                    final Intent verification = new Intent(
10686                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10687                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10688                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10689                            PACKAGE_MIME_TYPE);
10690                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10691
10692                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10693                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10694                            0 /* TODO: Which userId? */);
10695
10696                    if (DEBUG_VERIFY) {
10697                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10698                                + verification.toString() + " with " + pkgLite.verifiers.length
10699                                + " optional verifiers");
10700                    }
10701
10702                    final int verificationId = mPendingVerificationToken++;
10703
10704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10705
10706                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10707                            installerPackageName);
10708
10709                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10710                            installFlags);
10711
10712                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10713                            pkgLite.packageName);
10714
10715                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10716                            pkgLite.versionCode);
10717
10718                    if (verificationParams != null) {
10719                        if (verificationParams.getVerificationURI() != null) {
10720                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10721                                 verificationParams.getVerificationURI());
10722                        }
10723                        if (verificationParams.getOriginatingURI() != null) {
10724                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10725                                  verificationParams.getOriginatingURI());
10726                        }
10727                        if (verificationParams.getReferrer() != null) {
10728                            verification.putExtra(Intent.EXTRA_REFERRER,
10729                                  verificationParams.getReferrer());
10730                        }
10731                        if (verificationParams.getOriginatingUid() >= 0) {
10732                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10733                                  verificationParams.getOriginatingUid());
10734                        }
10735                        if (verificationParams.getInstallerUid() >= 0) {
10736                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10737                                  verificationParams.getInstallerUid());
10738                        }
10739                    }
10740
10741                    final PackageVerificationState verificationState = new PackageVerificationState(
10742                            requiredUid, args);
10743
10744                    mPendingVerification.append(verificationId, verificationState);
10745
10746                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10747                            receivers, verificationState);
10748
10749                    // Apps installed for "all" users use the device owner to verify the app
10750                    UserHandle verifierUser = getUser();
10751                    if (verifierUser == UserHandle.ALL) {
10752                        verifierUser = UserHandle.OWNER;
10753                    }
10754
10755                    /*
10756                     * If any sufficient verifiers were listed in the package
10757                     * manifest, attempt to ask them.
10758                     */
10759                    if (sufficientVerifiers != null) {
10760                        final int N = sufficientVerifiers.size();
10761                        if (N == 0) {
10762                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10763                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10764                        } else {
10765                            for (int i = 0; i < N; i++) {
10766                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10767
10768                                final Intent sufficientIntent = new Intent(verification);
10769                                sufficientIntent.setComponent(verifierComponent);
10770                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10771                            }
10772                        }
10773                    }
10774
10775                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10776                            mRequiredVerifierPackage, receivers);
10777                    if (ret == PackageManager.INSTALL_SUCCEEDED
10778                            && mRequiredVerifierPackage != null) {
10779                        /*
10780                         * Send the intent to the required verification agent,
10781                         * but only start the verification timeout after the
10782                         * target BroadcastReceivers have run.
10783                         */
10784                        verification.setComponent(requiredVerifierComponent);
10785                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10786                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10787                                new BroadcastReceiver() {
10788                                    @Override
10789                                    public void onReceive(Context context, Intent intent) {
10790                                        final Message msg = mHandler
10791                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10792                                        msg.arg1 = verificationId;
10793                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10794                                    }
10795                                }, null, 0, null, null);
10796
10797                        /*
10798                         * We don't want the copy to proceed until verification
10799                         * succeeds, so null out this field.
10800                         */
10801                        mArgs = null;
10802                    }
10803                } else {
10804                    /*
10805                     * No package verification is enabled, so immediately start
10806                     * the remote call to initiate copy using temporary file.
10807                     */
10808                    ret = args.copyApk(mContainerService, true);
10809                }
10810            }
10811
10812            mRet = ret;
10813        }
10814
10815        @Override
10816        void handleReturnCode() {
10817            // If mArgs is null, then MCS couldn't be reached. When it
10818            // reconnects, it will try again to install. At that point, this
10819            // will succeed.
10820            if (mArgs != null) {
10821                processPendingInstall(mArgs, mRet);
10822            }
10823        }
10824
10825        @Override
10826        void handleServiceError() {
10827            mArgs = createInstallArgs(this);
10828            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10829        }
10830
10831        public boolean isForwardLocked() {
10832            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10833        }
10834    }
10835
10836    /**
10837     * Used during creation of InstallArgs
10838     *
10839     * @param installFlags package installation flags
10840     * @return true if should be installed on external storage
10841     */
10842    private static boolean installOnExternalAsec(int installFlags) {
10843        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10844            return false;
10845        }
10846        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10847            return true;
10848        }
10849        return false;
10850    }
10851
10852    /**
10853     * Used during creation of InstallArgs
10854     *
10855     * @param installFlags package installation flags
10856     * @return true if should be installed as forward locked
10857     */
10858    private static boolean installForwardLocked(int installFlags) {
10859        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10860    }
10861
10862    private InstallArgs createInstallArgs(InstallParams params) {
10863        if (params.move != null) {
10864            return new MoveInstallArgs(params);
10865        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10866            return new AsecInstallArgs(params);
10867        } else {
10868            return new FileInstallArgs(params);
10869        }
10870    }
10871
10872    /**
10873     * Create args that describe an existing installed package. Typically used
10874     * when cleaning up old installs, or used as a move source.
10875     */
10876    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10877            String resourcePath, String[] instructionSets) {
10878        final boolean isInAsec;
10879        if (installOnExternalAsec(installFlags)) {
10880            /* Apps on SD card are always in ASEC containers. */
10881            isInAsec = true;
10882        } else if (installForwardLocked(installFlags)
10883                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10884            /*
10885             * Forward-locked apps are only in ASEC containers if they're the
10886             * new style
10887             */
10888            isInAsec = true;
10889        } else {
10890            isInAsec = false;
10891        }
10892
10893        if (isInAsec) {
10894            return new AsecInstallArgs(codePath, instructionSets,
10895                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10896        } else {
10897            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10898        }
10899    }
10900
10901    static abstract class InstallArgs {
10902        /** @see InstallParams#origin */
10903        final OriginInfo origin;
10904        /** @see InstallParams#move */
10905        final MoveInfo move;
10906
10907        final IPackageInstallObserver2 observer;
10908        // Always refers to PackageManager flags only
10909        final int installFlags;
10910        final String installerPackageName;
10911        final String volumeUuid;
10912        final ManifestDigest manifestDigest;
10913        final UserHandle user;
10914        final String abiOverride;
10915        final String[] installGrantPermissions;
10916
10917        // The list of instruction sets supported by this app. This is currently
10918        // only used during the rmdex() phase to clean up resources. We can get rid of this
10919        // if we move dex files under the common app path.
10920        /* nullable */ String[] instructionSets;
10921
10922        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10923                int installFlags, String installerPackageName, String volumeUuid,
10924                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10925                String abiOverride, String[] installGrantPermissions) {
10926            this.origin = origin;
10927            this.move = move;
10928            this.installFlags = installFlags;
10929            this.observer = observer;
10930            this.installerPackageName = installerPackageName;
10931            this.volumeUuid = volumeUuid;
10932            this.manifestDigest = manifestDigest;
10933            this.user = user;
10934            this.instructionSets = instructionSets;
10935            this.abiOverride = abiOverride;
10936            this.installGrantPermissions = installGrantPermissions;
10937        }
10938
10939        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10940        abstract int doPreInstall(int status);
10941
10942        /**
10943         * Rename package into final resting place. All paths on the given
10944         * scanned package should be updated to reflect the rename.
10945         */
10946        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10947        abstract int doPostInstall(int status, int uid);
10948
10949        /** @see PackageSettingBase#codePathString */
10950        abstract String getCodePath();
10951        /** @see PackageSettingBase#resourcePathString */
10952        abstract String getResourcePath();
10953
10954        // Need installer lock especially for dex file removal.
10955        abstract void cleanUpResourcesLI();
10956        abstract boolean doPostDeleteLI(boolean delete);
10957
10958        /**
10959         * Called before the source arguments are copied. This is used mostly
10960         * for MoveParams when it needs to read the source file to put it in the
10961         * destination.
10962         */
10963        int doPreCopy() {
10964            return PackageManager.INSTALL_SUCCEEDED;
10965        }
10966
10967        /**
10968         * Called after the source arguments are copied. This is used mostly for
10969         * MoveParams when it needs to read the source file to put it in the
10970         * destination.
10971         *
10972         * @return
10973         */
10974        int doPostCopy(int uid) {
10975            return PackageManager.INSTALL_SUCCEEDED;
10976        }
10977
10978        protected boolean isFwdLocked() {
10979            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10980        }
10981
10982        protected boolean isExternalAsec() {
10983            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10984        }
10985
10986        UserHandle getUser() {
10987            return user;
10988        }
10989    }
10990
10991    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10992        if (!allCodePaths.isEmpty()) {
10993            if (instructionSets == null) {
10994                throw new IllegalStateException("instructionSet == null");
10995            }
10996            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10997            for (String codePath : allCodePaths) {
10998                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10999                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11000                    if (retCode < 0) {
11001                        Slog.w(TAG, "Couldn't remove dex file for package: "
11002                                + " at location " + codePath + ", retcode=" + retCode);
11003                        // we don't consider this to be a failure of the core package deletion
11004                    }
11005                }
11006            }
11007        }
11008    }
11009
11010    /**
11011     * Logic to handle installation of non-ASEC applications, including copying
11012     * and renaming logic.
11013     */
11014    class FileInstallArgs extends InstallArgs {
11015        private File codeFile;
11016        private File resourceFile;
11017
11018        // Example topology:
11019        // /data/app/com.example/base.apk
11020        // /data/app/com.example/split_foo.apk
11021        // /data/app/com.example/lib/arm/libfoo.so
11022        // /data/app/com.example/lib/arm64/libfoo.so
11023        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11024
11025        /** New install */
11026        FileInstallArgs(InstallParams params) {
11027            super(params.origin, params.move, params.observer, params.installFlags,
11028                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11029                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11030                    params.grantedRuntimePermissions);
11031            if (isFwdLocked()) {
11032                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11033            }
11034        }
11035
11036        /** Existing install */
11037        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11038            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11039                    null, null);
11040            this.codeFile = (codePath != null) ? new File(codePath) : null;
11041            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11042        }
11043
11044        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11045            if (origin.staged) {
11046                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11047                codeFile = origin.file;
11048                resourceFile = origin.file;
11049                return PackageManager.INSTALL_SUCCEEDED;
11050            }
11051
11052            try {
11053                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11054                codeFile = tempDir;
11055                resourceFile = tempDir;
11056            } catch (IOException e) {
11057                Slog.w(TAG, "Failed to create copy file: " + e);
11058                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11059            }
11060
11061            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11062                @Override
11063                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11064                    if (!FileUtils.isValidExtFilename(name)) {
11065                        throw new IllegalArgumentException("Invalid filename: " + name);
11066                    }
11067                    try {
11068                        final File file = new File(codeFile, name);
11069                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11070                                O_RDWR | O_CREAT, 0644);
11071                        Os.chmod(file.getAbsolutePath(), 0644);
11072                        return new ParcelFileDescriptor(fd);
11073                    } catch (ErrnoException e) {
11074                        throw new RemoteException("Failed to open: " + e.getMessage());
11075                    }
11076                }
11077            };
11078
11079            int ret = PackageManager.INSTALL_SUCCEEDED;
11080            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11081            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11082                Slog.e(TAG, "Failed to copy package");
11083                return ret;
11084            }
11085
11086            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11087            NativeLibraryHelper.Handle handle = null;
11088            try {
11089                handle = NativeLibraryHelper.Handle.create(codeFile);
11090                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11091                        abiOverride);
11092            } catch (IOException e) {
11093                Slog.e(TAG, "Copying native libraries failed", e);
11094                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11095            } finally {
11096                IoUtils.closeQuietly(handle);
11097            }
11098
11099            return ret;
11100        }
11101
11102        int doPreInstall(int status) {
11103            if (status != PackageManager.INSTALL_SUCCEEDED) {
11104                cleanUp();
11105            }
11106            return status;
11107        }
11108
11109        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11110            if (status != PackageManager.INSTALL_SUCCEEDED) {
11111                cleanUp();
11112                return false;
11113            }
11114
11115            final File targetDir = codeFile.getParentFile();
11116            final File beforeCodeFile = codeFile;
11117            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11118
11119            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11120            try {
11121                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11122            } catch (ErrnoException e) {
11123                Slog.w(TAG, "Failed to rename", e);
11124                return false;
11125            }
11126
11127            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11128                Slog.w(TAG, "Failed to restorecon");
11129                return false;
11130            }
11131
11132            // Reflect the rename internally
11133            codeFile = afterCodeFile;
11134            resourceFile = afterCodeFile;
11135
11136            // Reflect the rename in scanned details
11137            pkg.codePath = afterCodeFile.getAbsolutePath();
11138            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11139                    pkg.baseCodePath);
11140            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11141                    pkg.splitCodePaths);
11142
11143            // Reflect the rename in app info
11144            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11145            pkg.applicationInfo.setCodePath(pkg.codePath);
11146            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11147            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11148            pkg.applicationInfo.setResourcePath(pkg.codePath);
11149            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11150            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11151
11152            return true;
11153        }
11154
11155        int doPostInstall(int status, int uid) {
11156            if (status != PackageManager.INSTALL_SUCCEEDED) {
11157                cleanUp();
11158            }
11159            return status;
11160        }
11161
11162        @Override
11163        String getCodePath() {
11164            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11165        }
11166
11167        @Override
11168        String getResourcePath() {
11169            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11170        }
11171
11172        private boolean cleanUp() {
11173            if (codeFile == null || !codeFile.exists()) {
11174                return false;
11175            }
11176
11177            if (codeFile.isDirectory()) {
11178                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11179            } else {
11180                codeFile.delete();
11181            }
11182
11183            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11184                resourceFile.delete();
11185            }
11186
11187            return true;
11188        }
11189
11190        void cleanUpResourcesLI() {
11191            // Try enumerating all code paths before deleting
11192            List<String> allCodePaths = Collections.EMPTY_LIST;
11193            if (codeFile != null && codeFile.exists()) {
11194                try {
11195                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11196                    allCodePaths = pkg.getAllCodePaths();
11197                } catch (PackageParserException e) {
11198                    // Ignored; we tried our best
11199                }
11200            }
11201
11202            cleanUp();
11203            removeDexFiles(allCodePaths, instructionSets);
11204        }
11205
11206        boolean doPostDeleteLI(boolean delete) {
11207            // XXX err, shouldn't we respect the delete flag?
11208            cleanUpResourcesLI();
11209            return true;
11210        }
11211    }
11212
11213    private boolean isAsecExternal(String cid) {
11214        final String asecPath = PackageHelper.getSdFilesystem(cid);
11215        return !asecPath.startsWith(mAsecInternalPath);
11216    }
11217
11218    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11219            PackageManagerException {
11220        if (copyRet < 0) {
11221            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11222                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11223                throw new PackageManagerException(copyRet, message);
11224            }
11225        }
11226    }
11227
11228    /**
11229     * Extract the MountService "container ID" from the full code path of an
11230     * .apk.
11231     */
11232    static String cidFromCodePath(String fullCodePath) {
11233        int eidx = fullCodePath.lastIndexOf("/");
11234        String subStr1 = fullCodePath.substring(0, eidx);
11235        int sidx = subStr1.lastIndexOf("/");
11236        return subStr1.substring(sidx+1, eidx);
11237    }
11238
11239    /**
11240     * Logic to handle installation of ASEC applications, including copying and
11241     * renaming logic.
11242     */
11243    class AsecInstallArgs extends InstallArgs {
11244        static final String RES_FILE_NAME = "pkg.apk";
11245        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11246
11247        String cid;
11248        String packagePath;
11249        String resourcePath;
11250
11251        /** New install */
11252        AsecInstallArgs(InstallParams params) {
11253            super(params.origin, params.move, params.observer, params.installFlags,
11254                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11255                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11256                    params.grantedRuntimePermissions);
11257        }
11258
11259        /** Existing install */
11260        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11261                        boolean isExternal, boolean isForwardLocked) {
11262            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11263                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11264                    instructionSets, null, null);
11265            // Hackily pretend we're still looking at a full code path
11266            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11267                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11268            }
11269
11270            // Extract cid from fullCodePath
11271            int eidx = fullCodePath.lastIndexOf("/");
11272            String subStr1 = fullCodePath.substring(0, eidx);
11273            int sidx = subStr1.lastIndexOf("/");
11274            cid = subStr1.substring(sidx+1, eidx);
11275            setMountPath(subStr1);
11276        }
11277
11278        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11279            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11280                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11281                    instructionSets, null, null);
11282            this.cid = cid;
11283            setMountPath(PackageHelper.getSdDir(cid));
11284        }
11285
11286        void createCopyFile() {
11287            cid = mInstallerService.allocateExternalStageCidLegacy();
11288        }
11289
11290        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11291            if (origin.staged) {
11292                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11293                cid = origin.cid;
11294                setMountPath(PackageHelper.getSdDir(cid));
11295                return PackageManager.INSTALL_SUCCEEDED;
11296            }
11297
11298            if (temp) {
11299                createCopyFile();
11300            } else {
11301                /*
11302                 * Pre-emptively destroy the container since it's destroyed if
11303                 * copying fails due to it existing anyway.
11304                 */
11305                PackageHelper.destroySdDir(cid);
11306            }
11307
11308            final String newMountPath = imcs.copyPackageToContainer(
11309                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11310                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11311
11312            if (newMountPath != null) {
11313                setMountPath(newMountPath);
11314                return PackageManager.INSTALL_SUCCEEDED;
11315            } else {
11316                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11317            }
11318        }
11319
11320        @Override
11321        String getCodePath() {
11322            return packagePath;
11323        }
11324
11325        @Override
11326        String getResourcePath() {
11327            return resourcePath;
11328        }
11329
11330        int doPreInstall(int status) {
11331            if (status != PackageManager.INSTALL_SUCCEEDED) {
11332                // Destroy container
11333                PackageHelper.destroySdDir(cid);
11334            } else {
11335                boolean mounted = PackageHelper.isContainerMounted(cid);
11336                if (!mounted) {
11337                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11338                            Process.SYSTEM_UID);
11339                    if (newMountPath != null) {
11340                        setMountPath(newMountPath);
11341                    } else {
11342                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11343                    }
11344                }
11345            }
11346            return status;
11347        }
11348
11349        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11350            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11351            String newMountPath = null;
11352            if (PackageHelper.isContainerMounted(cid)) {
11353                // Unmount the container
11354                if (!PackageHelper.unMountSdDir(cid)) {
11355                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11356                    return false;
11357                }
11358            }
11359            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11360                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11361                        " which might be stale. Will try to clean up.");
11362                // Clean up the stale container and proceed to recreate.
11363                if (!PackageHelper.destroySdDir(newCacheId)) {
11364                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11365                    return false;
11366                }
11367                // Successfully cleaned up stale container. Try to rename again.
11368                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11369                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11370                            + " inspite of cleaning it up.");
11371                    return false;
11372                }
11373            }
11374            if (!PackageHelper.isContainerMounted(newCacheId)) {
11375                Slog.w(TAG, "Mounting container " + newCacheId);
11376                newMountPath = PackageHelper.mountSdDir(newCacheId,
11377                        getEncryptKey(), Process.SYSTEM_UID);
11378            } else {
11379                newMountPath = PackageHelper.getSdDir(newCacheId);
11380            }
11381            if (newMountPath == null) {
11382                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11383                return false;
11384            }
11385            Log.i(TAG, "Succesfully renamed " + cid +
11386                    " to " + newCacheId +
11387                    " at new path: " + newMountPath);
11388            cid = newCacheId;
11389
11390            final File beforeCodeFile = new File(packagePath);
11391            setMountPath(newMountPath);
11392            final File afterCodeFile = new File(packagePath);
11393
11394            // Reflect the rename in scanned details
11395            pkg.codePath = afterCodeFile.getAbsolutePath();
11396            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11397                    pkg.baseCodePath);
11398            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11399                    pkg.splitCodePaths);
11400
11401            // Reflect the rename in app info
11402            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11403            pkg.applicationInfo.setCodePath(pkg.codePath);
11404            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11405            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11406            pkg.applicationInfo.setResourcePath(pkg.codePath);
11407            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11408            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11409
11410            return true;
11411        }
11412
11413        private void setMountPath(String mountPath) {
11414            final File mountFile = new File(mountPath);
11415
11416            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11417            if (monolithicFile.exists()) {
11418                packagePath = monolithicFile.getAbsolutePath();
11419                if (isFwdLocked()) {
11420                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11421                } else {
11422                    resourcePath = packagePath;
11423                }
11424            } else {
11425                packagePath = mountFile.getAbsolutePath();
11426                resourcePath = packagePath;
11427            }
11428        }
11429
11430        int doPostInstall(int status, int uid) {
11431            if (status != PackageManager.INSTALL_SUCCEEDED) {
11432                cleanUp();
11433            } else {
11434                final int groupOwner;
11435                final String protectedFile;
11436                if (isFwdLocked()) {
11437                    groupOwner = UserHandle.getSharedAppGid(uid);
11438                    protectedFile = RES_FILE_NAME;
11439                } else {
11440                    groupOwner = -1;
11441                    protectedFile = null;
11442                }
11443
11444                if (uid < Process.FIRST_APPLICATION_UID
11445                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11446                    Slog.e(TAG, "Failed to finalize " + cid);
11447                    PackageHelper.destroySdDir(cid);
11448                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11449                }
11450
11451                boolean mounted = PackageHelper.isContainerMounted(cid);
11452                if (!mounted) {
11453                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11454                }
11455            }
11456            return status;
11457        }
11458
11459        private void cleanUp() {
11460            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11461
11462            // Destroy secure container
11463            PackageHelper.destroySdDir(cid);
11464        }
11465
11466        private List<String> getAllCodePaths() {
11467            final File codeFile = new File(getCodePath());
11468            if (codeFile != null && codeFile.exists()) {
11469                try {
11470                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11471                    return pkg.getAllCodePaths();
11472                } catch (PackageParserException e) {
11473                    // Ignored; we tried our best
11474                }
11475            }
11476            return Collections.EMPTY_LIST;
11477        }
11478
11479        void cleanUpResourcesLI() {
11480            // Enumerate all code paths before deleting
11481            cleanUpResourcesLI(getAllCodePaths());
11482        }
11483
11484        private void cleanUpResourcesLI(List<String> allCodePaths) {
11485            cleanUp();
11486            removeDexFiles(allCodePaths, instructionSets);
11487        }
11488
11489        String getPackageName() {
11490            return getAsecPackageName(cid);
11491        }
11492
11493        boolean doPostDeleteLI(boolean delete) {
11494            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11495            final List<String> allCodePaths = getAllCodePaths();
11496            boolean mounted = PackageHelper.isContainerMounted(cid);
11497            if (mounted) {
11498                // Unmount first
11499                if (PackageHelper.unMountSdDir(cid)) {
11500                    mounted = false;
11501                }
11502            }
11503            if (!mounted && delete) {
11504                cleanUpResourcesLI(allCodePaths);
11505            }
11506            return !mounted;
11507        }
11508
11509        @Override
11510        int doPreCopy() {
11511            if (isFwdLocked()) {
11512                if (!PackageHelper.fixSdPermissions(cid,
11513                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11514                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11515                }
11516            }
11517
11518            return PackageManager.INSTALL_SUCCEEDED;
11519        }
11520
11521        @Override
11522        int doPostCopy(int uid) {
11523            if (isFwdLocked()) {
11524                if (uid < Process.FIRST_APPLICATION_UID
11525                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11526                                RES_FILE_NAME)) {
11527                    Slog.e(TAG, "Failed to finalize " + cid);
11528                    PackageHelper.destroySdDir(cid);
11529                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11530                }
11531            }
11532
11533            return PackageManager.INSTALL_SUCCEEDED;
11534        }
11535    }
11536
11537    /**
11538     * Logic to handle movement of existing installed applications.
11539     */
11540    class MoveInstallArgs extends InstallArgs {
11541        private File codeFile;
11542        private File resourceFile;
11543
11544        /** New install */
11545        MoveInstallArgs(InstallParams params) {
11546            super(params.origin, params.move, params.observer, params.installFlags,
11547                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11548                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11549                    params.grantedRuntimePermissions);
11550        }
11551
11552        int copyApk(IMediaContainerService imcs, boolean temp) {
11553            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11554                    + move.fromUuid + " to " + move.toUuid);
11555            synchronized (mInstaller) {
11556                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11557                        move.dataAppName, move.appId, move.seinfo) != 0) {
11558                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11559                }
11560            }
11561
11562            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11563            resourceFile = codeFile;
11564            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11565
11566            return PackageManager.INSTALL_SUCCEEDED;
11567        }
11568
11569        int doPreInstall(int status) {
11570            if (status != PackageManager.INSTALL_SUCCEEDED) {
11571                cleanUp(move.toUuid);
11572            }
11573            return status;
11574        }
11575
11576        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11577            if (status != PackageManager.INSTALL_SUCCEEDED) {
11578                cleanUp(move.toUuid);
11579                return false;
11580            }
11581
11582            // Reflect the move in app info
11583            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11584            pkg.applicationInfo.setCodePath(pkg.codePath);
11585            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11586            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11587            pkg.applicationInfo.setResourcePath(pkg.codePath);
11588            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11589            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11590
11591            return true;
11592        }
11593
11594        int doPostInstall(int status, int uid) {
11595            if (status == PackageManager.INSTALL_SUCCEEDED) {
11596                cleanUp(move.fromUuid);
11597            } else {
11598                cleanUp(move.toUuid);
11599            }
11600            return status;
11601        }
11602
11603        @Override
11604        String getCodePath() {
11605            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11606        }
11607
11608        @Override
11609        String getResourcePath() {
11610            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11611        }
11612
11613        private boolean cleanUp(String volumeUuid) {
11614            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11615                    move.dataAppName);
11616            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11617            synchronized (mInstallLock) {
11618                // Clean up both app data and code
11619                removeDataDirsLI(volumeUuid, move.packageName);
11620                if (codeFile.isDirectory()) {
11621                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11622                } else {
11623                    codeFile.delete();
11624                }
11625            }
11626            return true;
11627        }
11628
11629        void cleanUpResourcesLI() {
11630            throw new UnsupportedOperationException();
11631        }
11632
11633        boolean doPostDeleteLI(boolean delete) {
11634            throw new UnsupportedOperationException();
11635        }
11636    }
11637
11638    static String getAsecPackageName(String packageCid) {
11639        int idx = packageCid.lastIndexOf("-");
11640        if (idx == -1) {
11641            return packageCid;
11642        }
11643        return packageCid.substring(0, idx);
11644    }
11645
11646    // Utility method used to create code paths based on package name and available index.
11647    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11648        String idxStr = "";
11649        int idx = 1;
11650        // Fall back to default value of idx=1 if prefix is not
11651        // part of oldCodePath
11652        if (oldCodePath != null) {
11653            String subStr = oldCodePath;
11654            // Drop the suffix right away
11655            if (suffix != null && subStr.endsWith(suffix)) {
11656                subStr = subStr.substring(0, subStr.length() - suffix.length());
11657            }
11658            // If oldCodePath already contains prefix find out the
11659            // ending index to either increment or decrement.
11660            int sidx = subStr.lastIndexOf(prefix);
11661            if (sidx != -1) {
11662                subStr = subStr.substring(sidx + prefix.length());
11663                if (subStr != null) {
11664                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11665                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11666                    }
11667                    try {
11668                        idx = Integer.parseInt(subStr);
11669                        if (idx <= 1) {
11670                            idx++;
11671                        } else {
11672                            idx--;
11673                        }
11674                    } catch(NumberFormatException e) {
11675                    }
11676                }
11677            }
11678        }
11679        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11680        return prefix + idxStr;
11681    }
11682
11683    private File getNextCodePath(File targetDir, String packageName) {
11684        int suffix = 1;
11685        File result;
11686        do {
11687            result = new File(targetDir, packageName + "-" + suffix);
11688            suffix++;
11689        } while (result.exists());
11690        return result;
11691    }
11692
11693    // Utility method that returns the relative package path with respect
11694    // to the installation directory. Like say for /data/data/com.test-1.apk
11695    // string com.test-1 is returned.
11696    static String deriveCodePathName(String codePath) {
11697        if (codePath == null) {
11698            return null;
11699        }
11700        final File codeFile = new File(codePath);
11701        final String name = codeFile.getName();
11702        if (codeFile.isDirectory()) {
11703            return name;
11704        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11705            final int lastDot = name.lastIndexOf('.');
11706            return name.substring(0, lastDot);
11707        } else {
11708            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11709            return null;
11710        }
11711    }
11712
11713    class PackageInstalledInfo {
11714        String name;
11715        int uid;
11716        // The set of users that originally had this package installed.
11717        int[] origUsers;
11718        // The set of users that now have this package installed.
11719        int[] newUsers;
11720        PackageParser.Package pkg;
11721        int returnCode;
11722        String returnMsg;
11723        PackageRemovedInfo removedInfo;
11724
11725        public void setError(int code, String msg) {
11726            returnCode = code;
11727            returnMsg = msg;
11728            Slog.w(TAG, msg);
11729        }
11730
11731        public void setError(String msg, PackageParserException e) {
11732            returnCode = e.error;
11733            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11734            Slog.w(TAG, msg, e);
11735        }
11736
11737        public void setError(String msg, PackageManagerException e) {
11738            returnCode = e.error;
11739            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11740            Slog.w(TAG, msg, e);
11741        }
11742
11743        // In some error cases we want to convey more info back to the observer
11744        String origPackage;
11745        String origPermission;
11746    }
11747
11748    /*
11749     * Install a non-existing package.
11750     */
11751    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11752            UserHandle user, String installerPackageName, String volumeUuid,
11753            PackageInstalledInfo res) {
11754        // Remember this for later, in case we need to rollback this install
11755        String pkgName = pkg.packageName;
11756
11757        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11758        final boolean dataDirExists = Environment
11759                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11760        synchronized(mPackages) {
11761            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11762                // A package with the same name is already installed, though
11763                // it has been renamed to an older name.  The package we
11764                // are trying to install should be installed as an update to
11765                // the existing one, but that has not been requested, so bail.
11766                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11767                        + " without first uninstalling package running as "
11768                        + mSettings.mRenamedPackages.get(pkgName));
11769                return;
11770            }
11771            if (mPackages.containsKey(pkgName)) {
11772                // Don't allow installation over an existing package with the same name.
11773                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11774                        + " without first uninstalling.");
11775                return;
11776            }
11777        }
11778
11779        try {
11780            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11781                    System.currentTimeMillis(), user);
11782
11783            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11784            // delete the partially installed application. the data directory will have to be
11785            // restored if it was already existing
11786            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11787                // remove package from internal structures.  Note that we want deletePackageX to
11788                // delete the package data and cache directories that it created in
11789                // scanPackageLocked, unless those directories existed before we even tried to
11790                // install.
11791                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11792                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11793                                res.removedInfo, true);
11794            }
11795
11796        } catch (PackageManagerException e) {
11797            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11798        }
11799    }
11800
11801    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11802        // Can't rotate keys during boot or if sharedUser.
11803        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11804                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11805            return false;
11806        }
11807        // app is using upgradeKeySets; make sure all are valid
11808        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11809        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11810        for (int i = 0; i < upgradeKeySets.length; i++) {
11811            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11812                Slog.wtf(TAG, "Package "
11813                         + (oldPs.name != null ? oldPs.name : "<null>")
11814                         + " contains upgrade-key-set reference to unknown key-set: "
11815                         + upgradeKeySets[i]
11816                         + " reverting to signatures check.");
11817                return false;
11818            }
11819        }
11820        return true;
11821    }
11822
11823    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11824        // Upgrade keysets are being used.  Determine if new package has a superset of the
11825        // required keys.
11826        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11827        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11828        for (int i = 0; i < upgradeKeySets.length; i++) {
11829            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11830            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11831                return true;
11832            }
11833        }
11834        return false;
11835    }
11836
11837    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11838            UserHandle user, String installerPackageName, String volumeUuid,
11839            PackageInstalledInfo res) {
11840        final PackageParser.Package oldPackage;
11841        final String pkgName = pkg.packageName;
11842        final int[] allUsers;
11843        final boolean[] perUserInstalled;
11844
11845        // First find the old package info and check signatures
11846        synchronized(mPackages) {
11847            oldPackage = mPackages.get(pkgName);
11848            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11849            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11850            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11851                if(!checkUpgradeKeySetLP(ps, pkg)) {
11852                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11853                            "New package not signed by keys specified by upgrade-keysets: "
11854                            + pkgName);
11855                    return;
11856                }
11857            } else {
11858                // default to original signature matching
11859                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11860                    != PackageManager.SIGNATURE_MATCH) {
11861                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11862                            "New package has a different signature: " + pkgName);
11863                    return;
11864                }
11865            }
11866
11867            // In case of rollback, remember per-user/profile install state
11868            allUsers = sUserManager.getUserIds();
11869            perUserInstalled = new boolean[allUsers.length];
11870            for (int i = 0; i < allUsers.length; i++) {
11871                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11872            }
11873        }
11874
11875        boolean sysPkg = (isSystemApp(oldPackage));
11876        if (sysPkg) {
11877            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11878                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11879        } else {
11880            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11881                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11882        }
11883    }
11884
11885    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11886            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11887            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11888            String volumeUuid, PackageInstalledInfo res) {
11889        String pkgName = deletedPackage.packageName;
11890        boolean deletedPkg = true;
11891        boolean updatedSettings = false;
11892
11893        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11894                + deletedPackage);
11895        long origUpdateTime;
11896        if (pkg.mExtras != null) {
11897            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11898        } else {
11899            origUpdateTime = 0;
11900        }
11901
11902        // First delete the existing package while retaining the data directory
11903        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11904                res.removedInfo, true)) {
11905            // If the existing package wasn't successfully deleted
11906            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11907            deletedPkg = false;
11908        } else {
11909            // Successfully deleted the old package; proceed with replace.
11910
11911            // If deleted package lived in a container, give users a chance to
11912            // relinquish resources before killing.
11913            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11914                if (DEBUG_INSTALL) {
11915                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11916                }
11917                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11918                final ArrayList<String> pkgList = new ArrayList<String>(1);
11919                pkgList.add(deletedPackage.applicationInfo.packageName);
11920                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11921            }
11922
11923            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11924            try {
11925                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11926                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11927                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11928                        perUserInstalled, res, user);
11929                updatedSettings = true;
11930            } catch (PackageManagerException e) {
11931                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11932            }
11933        }
11934
11935        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11936            // remove package from internal structures.  Note that we want deletePackageX to
11937            // delete the package data and cache directories that it created in
11938            // scanPackageLocked, unless those directories existed before we even tried to
11939            // install.
11940            if(updatedSettings) {
11941                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11942                deletePackageLI(
11943                        pkgName, null, true, allUsers, perUserInstalled,
11944                        PackageManager.DELETE_KEEP_DATA,
11945                                res.removedInfo, true);
11946            }
11947            // Since we failed to install the new package we need to restore the old
11948            // package that we deleted.
11949            if (deletedPkg) {
11950                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11951                File restoreFile = new File(deletedPackage.codePath);
11952                // Parse old package
11953                boolean oldExternal = isExternal(deletedPackage);
11954                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11955                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11956                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11957                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11958                try {
11959                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11960                } catch (PackageManagerException e) {
11961                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11962                            + e.getMessage());
11963                    return;
11964                }
11965                // Restore of old package succeeded. Update permissions.
11966                // writer
11967                synchronized (mPackages) {
11968                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11969                            UPDATE_PERMISSIONS_ALL);
11970                    // can downgrade to reader
11971                    mSettings.writeLPr();
11972                }
11973                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11974            }
11975        }
11976    }
11977
11978    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11979            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11980            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11981            String volumeUuid, PackageInstalledInfo res) {
11982        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11983                + ", old=" + deletedPackage);
11984        boolean disabledSystem = false;
11985        boolean updatedSettings = false;
11986        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11987        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11988                != 0) {
11989            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11990        }
11991        String packageName = deletedPackage.packageName;
11992        if (packageName == null) {
11993            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11994                    "Attempt to delete null packageName.");
11995            return;
11996        }
11997        PackageParser.Package oldPkg;
11998        PackageSetting oldPkgSetting;
11999        // reader
12000        synchronized (mPackages) {
12001            oldPkg = mPackages.get(packageName);
12002            oldPkgSetting = mSettings.mPackages.get(packageName);
12003            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12004                    (oldPkgSetting == null)) {
12005                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12006                        "Couldn't find package:" + packageName + " information");
12007                return;
12008            }
12009        }
12010
12011        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12012
12013        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12014        res.removedInfo.removedPackage = packageName;
12015        // Remove existing system package
12016        removePackageLI(oldPkgSetting, true);
12017        // writer
12018        synchronized (mPackages) {
12019            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12020            if (!disabledSystem && deletedPackage != null) {
12021                // We didn't need to disable the .apk as a current system package,
12022                // which means we are replacing another update that is already
12023                // installed.  We need to make sure to delete the older one's .apk.
12024                res.removedInfo.args = createInstallArgsForExisting(0,
12025                        deletedPackage.applicationInfo.getCodePath(),
12026                        deletedPackage.applicationInfo.getResourcePath(),
12027                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12028            } else {
12029                res.removedInfo.args = null;
12030            }
12031        }
12032
12033        // Successfully disabled the old package. Now proceed with re-installation
12034        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12035
12036        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12037        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12038
12039        PackageParser.Package newPackage = null;
12040        try {
12041            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12042            if (newPackage.mExtras != null) {
12043                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12044                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12045                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12046
12047                // is the update attempting to change shared user? that isn't going to work...
12048                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12049                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12050                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12051                            + " to " + newPkgSetting.sharedUser);
12052                    updatedSettings = true;
12053                }
12054            }
12055
12056            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12057                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12058                        perUserInstalled, res, user);
12059                updatedSettings = true;
12060            }
12061
12062        } catch (PackageManagerException e) {
12063            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12064        }
12065
12066        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12067            // Re installation failed. Restore old information
12068            // Remove new pkg information
12069            if (newPackage != null) {
12070                removeInstalledPackageLI(newPackage, true);
12071            }
12072            // Add back the old system package
12073            try {
12074                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12075            } catch (PackageManagerException e) {
12076                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12077            }
12078            // Restore the old system information in Settings
12079            synchronized (mPackages) {
12080                if (disabledSystem) {
12081                    mSettings.enableSystemPackageLPw(packageName);
12082                }
12083                if (updatedSettings) {
12084                    mSettings.setInstallerPackageName(packageName,
12085                            oldPkgSetting.installerPackageName);
12086                }
12087                mSettings.writeLPr();
12088            }
12089        }
12090    }
12091
12092    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12093            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12094            UserHandle user) {
12095        String pkgName = newPackage.packageName;
12096        synchronized (mPackages) {
12097            //write settings. the installStatus will be incomplete at this stage.
12098            //note that the new package setting would have already been
12099            //added to mPackages. It hasn't been persisted yet.
12100            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12101            mSettings.writeLPr();
12102        }
12103
12104        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12105
12106        synchronized (mPackages) {
12107            updatePermissionsLPw(newPackage.packageName, newPackage,
12108                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12109                            ? UPDATE_PERMISSIONS_ALL : 0));
12110            // For system-bundled packages, we assume that installing an upgraded version
12111            // of the package implies that the user actually wants to run that new code,
12112            // so we enable the package.
12113            PackageSetting ps = mSettings.mPackages.get(pkgName);
12114            if (ps != null) {
12115                if (isSystemApp(newPackage)) {
12116                    // NB: implicit assumption that system package upgrades apply to all users
12117                    if (DEBUG_INSTALL) {
12118                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12119                    }
12120                    if (res.origUsers != null) {
12121                        for (int userHandle : res.origUsers) {
12122                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12123                                    userHandle, installerPackageName);
12124                        }
12125                    }
12126                    // Also convey the prior install/uninstall state
12127                    if (allUsers != null && perUserInstalled != null) {
12128                        for (int i = 0; i < allUsers.length; i++) {
12129                            if (DEBUG_INSTALL) {
12130                                Slog.d(TAG, "    user " + allUsers[i]
12131                                        + " => " + perUserInstalled[i]);
12132                            }
12133                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12134                        }
12135                        // these install state changes will be persisted in the
12136                        // upcoming call to mSettings.writeLPr().
12137                    }
12138                }
12139                // It's implied that when a user requests installation, they want the app to be
12140                // installed and enabled.
12141                int userId = user.getIdentifier();
12142                if (userId != UserHandle.USER_ALL) {
12143                    ps.setInstalled(true, userId);
12144                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12145                }
12146            }
12147            res.name = pkgName;
12148            res.uid = newPackage.applicationInfo.uid;
12149            res.pkg = newPackage;
12150            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12151            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12152            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12153            //to update install status
12154            mSettings.writeLPr();
12155        }
12156    }
12157
12158    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12159        final int installFlags = args.installFlags;
12160        final String installerPackageName = args.installerPackageName;
12161        final String volumeUuid = args.volumeUuid;
12162        final File tmpPackageFile = new File(args.getCodePath());
12163        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12164        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12165                || (args.volumeUuid != null));
12166        boolean replace = false;
12167        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12168        if (args.move != null) {
12169            // moving a complete application; perfom an initial scan on the new install location
12170            scanFlags |= SCAN_INITIAL;
12171        }
12172        // Result object to be returned
12173        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12174
12175        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12176        // Retrieve PackageSettings and parse package
12177        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12178                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12179                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12180        PackageParser pp = new PackageParser();
12181        pp.setSeparateProcesses(mSeparateProcesses);
12182        pp.setDisplayMetrics(mMetrics);
12183
12184        final PackageParser.Package pkg;
12185        try {
12186            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12187        } catch (PackageParserException e) {
12188            res.setError("Failed parse during installPackageLI", e);
12189            return;
12190        }
12191
12192        // Mark that we have an install time CPU ABI override.
12193        pkg.cpuAbiOverride = args.abiOverride;
12194
12195        String pkgName = res.name = pkg.packageName;
12196        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12197            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12198                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12199                return;
12200            }
12201        }
12202
12203        try {
12204            pp.collectCertificates(pkg, parseFlags);
12205            pp.collectManifestDigest(pkg);
12206        } catch (PackageParserException e) {
12207            res.setError("Failed collect during installPackageLI", e);
12208            return;
12209        }
12210
12211        /* If the installer passed in a manifest digest, compare it now. */
12212        if (args.manifestDigest != null) {
12213            if (DEBUG_INSTALL) {
12214                final String parsedManifest = pkg.manifestDigest == null ? "null"
12215                        : pkg.manifestDigest.toString();
12216                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12217                        + parsedManifest);
12218            }
12219
12220            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12221                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12222                return;
12223            }
12224        } else if (DEBUG_INSTALL) {
12225            final String parsedManifest = pkg.manifestDigest == null
12226                    ? "null" : pkg.manifestDigest.toString();
12227            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12228        }
12229
12230        // Get rid of all references to package scan path via parser.
12231        pp = null;
12232        String oldCodePath = null;
12233        boolean systemApp = false;
12234        synchronized (mPackages) {
12235            // Check if installing already existing package
12236            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12237                String oldName = mSettings.mRenamedPackages.get(pkgName);
12238                if (pkg.mOriginalPackages != null
12239                        && pkg.mOriginalPackages.contains(oldName)
12240                        && mPackages.containsKey(oldName)) {
12241                    // This package is derived from an original package,
12242                    // and this device has been updating from that original
12243                    // name.  We must continue using the original name, so
12244                    // rename the new package here.
12245                    pkg.setPackageName(oldName);
12246                    pkgName = pkg.packageName;
12247                    replace = true;
12248                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12249                            + oldName + " pkgName=" + pkgName);
12250                } else if (mPackages.containsKey(pkgName)) {
12251                    // This package, under its official name, already exists
12252                    // on the device; we should replace it.
12253                    replace = true;
12254                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12255                }
12256
12257                // Prevent apps opting out from runtime permissions
12258                if (replace) {
12259                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12260                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12261                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12262                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12263                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12264                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12265                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12266                                        + " doesn't support runtime permissions but the old"
12267                                        + " target SDK " + oldTargetSdk + " does.");
12268                        return;
12269                    }
12270                }
12271            }
12272
12273            PackageSetting ps = mSettings.mPackages.get(pkgName);
12274            if (ps != null) {
12275                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12276
12277                // Quick sanity check that we're signed correctly if updating;
12278                // we'll check this again later when scanning, but we want to
12279                // bail early here before tripping over redefined permissions.
12280                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12281                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12282                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12283                                + pkg.packageName + " upgrade keys do not match the "
12284                                + "previously installed version");
12285                        return;
12286                    }
12287                } else {
12288                    try {
12289                        verifySignaturesLP(ps, pkg);
12290                    } catch (PackageManagerException e) {
12291                        res.setError(e.error, e.getMessage());
12292                        return;
12293                    }
12294                }
12295
12296                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12297                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12298                    systemApp = (ps.pkg.applicationInfo.flags &
12299                            ApplicationInfo.FLAG_SYSTEM) != 0;
12300                }
12301                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12302            }
12303
12304            // Check whether the newly-scanned package wants to define an already-defined perm
12305            int N = pkg.permissions.size();
12306            for (int i = N-1; i >= 0; i--) {
12307                PackageParser.Permission perm = pkg.permissions.get(i);
12308                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12309                if (bp != null) {
12310                    // If the defining package is signed with our cert, it's okay.  This
12311                    // also includes the "updating the same package" case, of course.
12312                    // "updating same package" could also involve key-rotation.
12313                    final boolean sigsOk;
12314                    if (bp.sourcePackage.equals(pkg.packageName)
12315                            && (bp.packageSetting instanceof PackageSetting)
12316                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12317                                    scanFlags))) {
12318                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12319                    } else {
12320                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12321                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12322                    }
12323                    if (!sigsOk) {
12324                        // If the owning package is the system itself, we log but allow
12325                        // install to proceed; we fail the install on all other permission
12326                        // redefinitions.
12327                        if (!bp.sourcePackage.equals("android")) {
12328                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12329                                    + pkg.packageName + " attempting to redeclare permission "
12330                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12331                            res.origPermission = perm.info.name;
12332                            res.origPackage = bp.sourcePackage;
12333                            return;
12334                        } else {
12335                            Slog.w(TAG, "Package " + pkg.packageName
12336                                    + " attempting to redeclare system permission "
12337                                    + perm.info.name + "; ignoring new declaration");
12338                            pkg.permissions.remove(i);
12339                        }
12340                    }
12341                }
12342            }
12343
12344        }
12345
12346        if (systemApp && onExternal) {
12347            // Disable updates to system apps on sdcard
12348            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12349                    "Cannot install updates to system apps on sdcard");
12350            return;
12351        }
12352
12353        if (args.move != null) {
12354            // We did an in-place move, so dex is ready to roll
12355            scanFlags |= SCAN_NO_DEX;
12356            scanFlags |= SCAN_MOVE;
12357
12358            synchronized (mPackages) {
12359                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12360                if (ps == null) {
12361                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12362                            "Missing settings for moved package " + pkgName);
12363                }
12364
12365                // We moved the entire application as-is, so bring over the
12366                // previously derived ABI information.
12367                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12368                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12369            }
12370
12371        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12372            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12373            scanFlags |= SCAN_NO_DEX;
12374
12375            try {
12376                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12377                        true /* extract libs */);
12378            } catch (PackageManagerException pme) {
12379                Slog.e(TAG, "Error deriving application ABI", pme);
12380                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12381                return;
12382            }
12383
12384            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12385            int result = mPackageDexOptimizer
12386                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12387                            false /* defer */, false /* inclDependencies */,
12388                            true /* boot complete */);
12389            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12390                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12391                return;
12392            }
12393        }
12394
12395        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12396            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12397            return;
12398        }
12399
12400        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12401
12402        if (replace) {
12403            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12404                    installerPackageName, volumeUuid, res);
12405        } else {
12406            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12407                    args.user, installerPackageName, volumeUuid, res);
12408        }
12409        synchronized (mPackages) {
12410            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12411            if (ps != null) {
12412                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12413            }
12414        }
12415    }
12416
12417    private void startIntentFilterVerifications(int userId, boolean replacing,
12418            PackageParser.Package pkg) {
12419        if (mIntentFilterVerifierComponent == null) {
12420            Slog.w(TAG, "No IntentFilter verification will not be done as "
12421                    + "there is no IntentFilterVerifier available!");
12422            return;
12423        }
12424
12425        final int verifierUid = getPackageUid(
12426                mIntentFilterVerifierComponent.getPackageName(),
12427                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12428
12429        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12430        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12431        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12432        mHandler.sendMessage(msg);
12433    }
12434
12435    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12436            PackageParser.Package pkg) {
12437        int size = pkg.activities.size();
12438        if (size == 0) {
12439            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12440                    "No activity, so no need to verify any IntentFilter!");
12441            return;
12442        }
12443
12444        final boolean hasDomainURLs = hasDomainURLs(pkg);
12445        if (!hasDomainURLs) {
12446            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12447                    "No domain URLs, so no need to verify any IntentFilter!");
12448            return;
12449        }
12450
12451        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12452                + " if any IntentFilter from the " + size
12453                + " Activities needs verification ...");
12454
12455        int count = 0;
12456        final String packageName = pkg.packageName;
12457
12458        synchronized (mPackages) {
12459            // If this is a new install and we see that we've already run verification for this
12460            // package, we have nothing to do: it means the state was restored from backup.
12461            if (!replacing) {
12462                IntentFilterVerificationInfo ivi =
12463                        mSettings.getIntentFilterVerificationLPr(packageName);
12464                if (ivi != null) {
12465                    if (DEBUG_DOMAIN_VERIFICATION) {
12466                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12467                                + ivi.getStatusString());
12468                    }
12469                    return;
12470                }
12471            }
12472
12473            // If any filters need to be verified, then all need to be.
12474            boolean needToVerify = false;
12475            for (PackageParser.Activity a : pkg.activities) {
12476                for (ActivityIntentInfo filter : a.intents) {
12477                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12478                        if (DEBUG_DOMAIN_VERIFICATION) {
12479                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12480                        }
12481                        needToVerify = true;
12482                        break;
12483                    }
12484                }
12485            }
12486
12487            if (needToVerify) {
12488                final int verificationId = mIntentFilterVerificationToken++;
12489                for (PackageParser.Activity a : pkg.activities) {
12490                    for (ActivityIntentInfo filter : a.intents) {
12491                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12492                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12493                                    "Verification needed for IntentFilter:" + filter.toString());
12494                            mIntentFilterVerifier.addOneIntentFilterVerification(
12495                                    verifierUid, userId, verificationId, filter, packageName);
12496                            count++;
12497                        }
12498                    }
12499                }
12500            }
12501        }
12502
12503        if (count > 0) {
12504            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12505                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12506                    +  " for userId:" + userId);
12507            mIntentFilterVerifier.startVerifications(userId);
12508        } else {
12509            if (DEBUG_DOMAIN_VERIFICATION) {
12510                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12511            }
12512        }
12513    }
12514
12515    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12516        final ComponentName cn  = filter.activity.getComponentName();
12517        final String packageName = cn.getPackageName();
12518
12519        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12520                packageName);
12521        if (ivi == null) {
12522            return true;
12523        }
12524        int status = ivi.getStatus();
12525        switch (status) {
12526            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12527            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12528                return true;
12529
12530            default:
12531                // Nothing to do
12532                return false;
12533        }
12534    }
12535
12536    private static boolean isMultiArch(PackageSetting ps) {
12537        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12538    }
12539
12540    private static boolean isMultiArch(ApplicationInfo info) {
12541        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12542    }
12543
12544    private static boolean isExternal(PackageParser.Package pkg) {
12545        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12546    }
12547
12548    private static boolean isExternal(PackageSetting ps) {
12549        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12550    }
12551
12552    private static boolean isExternal(ApplicationInfo info) {
12553        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12554    }
12555
12556    private static boolean isSystemApp(PackageParser.Package pkg) {
12557        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12558    }
12559
12560    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12561        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12562    }
12563
12564    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12565        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12566    }
12567
12568    private static boolean isSystemApp(PackageSetting ps) {
12569        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12570    }
12571
12572    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12573        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12574    }
12575
12576    private int packageFlagsToInstallFlags(PackageSetting ps) {
12577        int installFlags = 0;
12578        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12579            // This existing package was an external ASEC install when we have
12580            // the external flag without a UUID
12581            installFlags |= PackageManager.INSTALL_EXTERNAL;
12582        }
12583        if (ps.isForwardLocked()) {
12584            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12585        }
12586        return installFlags;
12587    }
12588
12589    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12590        if (isExternal(pkg)) {
12591            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12592                return mSettings.getExternalVersion();
12593            } else {
12594                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12595            }
12596        } else {
12597            return mSettings.getInternalVersion();
12598        }
12599    }
12600
12601    private void deleteTempPackageFiles() {
12602        final FilenameFilter filter = new FilenameFilter() {
12603            public boolean accept(File dir, String name) {
12604                return name.startsWith("vmdl") && name.endsWith(".tmp");
12605            }
12606        };
12607        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12608            file.delete();
12609        }
12610    }
12611
12612    @Override
12613    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12614            int flags) {
12615        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12616                flags);
12617    }
12618
12619    @Override
12620    public void deletePackage(final String packageName,
12621            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12622        mContext.enforceCallingOrSelfPermission(
12623                android.Manifest.permission.DELETE_PACKAGES, null);
12624        Preconditions.checkNotNull(packageName);
12625        Preconditions.checkNotNull(observer);
12626        final int uid = Binder.getCallingUid();
12627        if (UserHandle.getUserId(uid) != userId) {
12628            mContext.enforceCallingPermission(
12629                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12630                    "deletePackage for user " + userId);
12631        }
12632        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12633            try {
12634                observer.onPackageDeleted(packageName,
12635                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12636            } catch (RemoteException re) {
12637            }
12638            return;
12639        }
12640
12641        boolean uninstallBlocked = false;
12642        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12643            int[] users = sUserManager.getUserIds();
12644            for (int i = 0; i < users.length; ++i) {
12645                if (getBlockUninstallForUser(packageName, users[i])) {
12646                    uninstallBlocked = true;
12647                    break;
12648                }
12649            }
12650        } else {
12651            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12652        }
12653        if (uninstallBlocked) {
12654            try {
12655                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12656                        null);
12657            } catch (RemoteException re) {
12658            }
12659            return;
12660        }
12661
12662        if (DEBUG_REMOVE) {
12663            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12664        }
12665        // Queue up an async operation since the package deletion may take a little while.
12666        mHandler.post(new Runnable() {
12667            public void run() {
12668                mHandler.removeCallbacks(this);
12669                final int returnCode = deletePackageX(packageName, userId, flags);
12670                if (observer != null) {
12671                    try {
12672                        observer.onPackageDeleted(packageName, returnCode, null);
12673                    } catch (RemoteException e) {
12674                        Log.i(TAG, "Observer no longer exists.");
12675                    } //end catch
12676                } //end if
12677            } //end run
12678        });
12679    }
12680
12681    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12682        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12683                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12684        try {
12685            if (dpm != null) {
12686                if (dpm.isDeviceOwner(packageName)) {
12687                    return true;
12688                }
12689                int[] users;
12690                if (userId == UserHandle.USER_ALL) {
12691                    users = sUserManager.getUserIds();
12692                } else {
12693                    users = new int[]{userId};
12694                }
12695                for (int i = 0; i < users.length; ++i) {
12696                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12697                        return true;
12698                    }
12699                }
12700            }
12701        } catch (RemoteException e) {
12702        }
12703        return false;
12704    }
12705
12706    /**
12707     *  This method is an internal method that could be get invoked either
12708     *  to delete an installed package or to clean up a failed installation.
12709     *  After deleting an installed package, a broadcast is sent to notify any
12710     *  listeners that the package has been installed. For cleaning up a failed
12711     *  installation, the broadcast is not necessary since the package's
12712     *  installation wouldn't have sent the initial broadcast either
12713     *  The key steps in deleting a package are
12714     *  deleting the package information in internal structures like mPackages,
12715     *  deleting the packages base directories through installd
12716     *  updating mSettings to reflect current status
12717     *  persisting settings for later use
12718     *  sending a broadcast if necessary
12719     */
12720    private int deletePackageX(String packageName, int userId, int flags) {
12721        final PackageRemovedInfo info = new PackageRemovedInfo();
12722        final boolean res;
12723
12724        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12725                ? UserHandle.ALL : new UserHandle(userId);
12726
12727        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12728            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12729            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12730        }
12731
12732        boolean removedForAllUsers = false;
12733        boolean systemUpdate = false;
12734
12735        // for the uninstall-updates case and restricted profiles, remember the per-
12736        // userhandle installed state
12737        int[] allUsers;
12738        boolean[] perUserInstalled;
12739        synchronized (mPackages) {
12740            PackageSetting ps = mSettings.mPackages.get(packageName);
12741            allUsers = sUserManager.getUserIds();
12742            perUserInstalled = new boolean[allUsers.length];
12743            for (int i = 0; i < allUsers.length; i++) {
12744                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12745            }
12746        }
12747
12748        synchronized (mInstallLock) {
12749            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12750            res = deletePackageLI(packageName, removeForUser,
12751                    true, allUsers, perUserInstalled,
12752                    flags | REMOVE_CHATTY, info, true);
12753            systemUpdate = info.isRemovedPackageSystemUpdate;
12754            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12755                removedForAllUsers = true;
12756            }
12757            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12758                    + " removedForAllUsers=" + removedForAllUsers);
12759        }
12760
12761        if (res) {
12762            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12763
12764            // If the removed package was a system update, the old system package
12765            // was re-enabled; we need to broadcast this information
12766            if (systemUpdate) {
12767                Bundle extras = new Bundle(1);
12768                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12769                        ? info.removedAppId : info.uid);
12770                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12771
12772                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12773                        extras, null, null, null);
12774                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12775                        extras, null, null, null);
12776                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12777                        null, packageName, null, null);
12778            }
12779        }
12780        // Force a gc here.
12781        Runtime.getRuntime().gc();
12782        // Delete the resources here after sending the broadcast to let
12783        // other processes clean up before deleting resources.
12784        if (info.args != null) {
12785            synchronized (mInstallLock) {
12786                info.args.doPostDeleteLI(true);
12787            }
12788        }
12789
12790        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12791    }
12792
12793    class PackageRemovedInfo {
12794        String removedPackage;
12795        int uid = -1;
12796        int removedAppId = -1;
12797        int[] removedUsers = null;
12798        boolean isRemovedPackageSystemUpdate = false;
12799        // Clean up resources deleted packages.
12800        InstallArgs args = null;
12801
12802        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12803            Bundle extras = new Bundle(1);
12804            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12805            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12806            if (replacing) {
12807                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12808            }
12809            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12810            if (removedPackage != null) {
12811                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12812                        extras, null, null, removedUsers);
12813                if (fullRemove && !replacing) {
12814                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12815                            extras, null, null, removedUsers);
12816                }
12817            }
12818            if (removedAppId >= 0) {
12819                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12820                        removedUsers);
12821            }
12822        }
12823    }
12824
12825    /*
12826     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12827     * flag is not set, the data directory is removed as well.
12828     * make sure this flag is set for partially installed apps. If not its meaningless to
12829     * delete a partially installed application.
12830     */
12831    private void removePackageDataLI(PackageSetting ps,
12832            int[] allUserHandles, boolean[] perUserInstalled,
12833            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12834        String packageName = ps.name;
12835        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12836        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12837        // Retrieve object to delete permissions for shared user later on
12838        final PackageSetting deletedPs;
12839        // reader
12840        synchronized (mPackages) {
12841            deletedPs = mSettings.mPackages.get(packageName);
12842            if (outInfo != null) {
12843                outInfo.removedPackage = packageName;
12844                outInfo.removedUsers = deletedPs != null
12845                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12846                        : null;
12847            }
12848        }
12849        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12850            removeDataDirsLI(ps.volumeUuid, packageName);
12851            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12852        }
12853        // writer
12854        synchronized (mPackages) {
12855            if (deletedPs != null) {
12856                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12857                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12858                    clearDefaultBrowserIfNeeded(packageName);
12859                    if (outInfo != null) {
12860                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12861                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12862                    }
12863                    updatePermissionsLPw(deletedPs.name, null, 0);
12864                    if (deletedPs.sharedUser != null) {
12865                        // Remove permissions associated with package. Since runtime
12866                        // permissions are per user we have to kill the removed package
12867                        // or packages running under the shared user of the removed
12868                        // package if revoking the permissions requested only by the removed
12869                        // package is successful and this causes a change in gids.
12870                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12871                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12872                                    userId);
12873                            if (userIdToKill == UserHandle.USER_ALL
12874                                    || userIdToKill >= UserHandle.USER_OWNER) {
12875                                // If gids changed for this user, kill all affected packages.
12876                                mHandler.post(new Runnable() {
12877                                    @Override
12878                                    public void run() {
12879                                        // This has to happen with no lock held.
12880                                        killApplication(deletedPs.name, deletedPs.appId,
12881                                                KILL_APP_REASON_GIDS_CHANGED);
12882                                    }
12883                                });
12884                                break;
12885                            }
12886                        }
12887                    }
12888                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12889                }
12890                // make sure to preserve per-user disabled state if this removal was just
12891                // a downgrade of a system app to the factory package
12892                if (allUserHandles != null && perUserInstalled != null) {
12893                    if (DEBUG_REMOVE) {
12894                        Slog.d(TAG, "Propagating install state across downgrade");
12895                    }
12896                    for (int i = 0; i < allUserHandles.length; i++) {
12897                        if (DEBUG_REMOVE) {
12898                            Slog.d(TAG, "    user " + allUserHandles[i]
12899                                    + " => " + perUserInstalled[i]);
12900                        }
12901                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12902                    }
12903                }
12904            }
12905            // can downgrade to reader
12906            if (writeSettings) {
12907                // Save settings now
12908                mSettings.writeLPr();
12909            }
12910        }
12911        if (outInfo != null) {
12912            // A user ID was deleted here. Go through all users and remove it
12913            // from KeyStore.
12914            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12915        }
12916    }
12917
12918    static boolean locationIsPrivileged(File path) {
12919        try {
12920            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12921                    .getCanonicalPath();
12922            return path.getCanonicalPath().startsWith(privilegedAppDir);
12923        } catch (IOException e) {
12924            Slog.e(TAG, "Unable to access code path " + path);
12925        }
12926        return false;
12927    }
12928
12929    /*
12930     * Tries to delete system package.
12931     */
12932    private boolean deleteSystemPackageLI(PackageSetting newPs,
12933            int[] allUserHandles, boolean[] perUserInstalled,
12934            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12935        final boolean applyUserRestrictions
12936                = (allUserHandles != null) && (perUserInstalled != null);
12937        PackageSetting disabledPs = null;
12938        // Confirm if the system package has been updated
12939        // An updated system app can be deleted. This will also have to restore
12940        // the system pkg from system partition
12941        // reader
12942        synchronized (mPackages) {
12943            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12944        }
12945        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12946                + " disabledPs=" + disabledPs);
12947        if (disabledPs == null) {
12948            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12949            return false;
12950        } else if (DEBUG_REMOVE) {
12951            Slog.d(TAG, "Deleting system pkg from data partition");
12952        }
12953        if (DEBUG_REMOVE) {
12954            if (applyUserRestrictions) {
12955                Slog.d(TAG, "Remembering install states:");
12956                for (int i = 0; i < allUserHandles.length; i++) {
12957                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12958                }
12959            }
12960        }
12961        // Delete the updated package
12962        outInfo.isRemovedPackageSystemUpdate = true;
12963        if (disabledPs.versionCode < newPs.versionCode) {
12964            // Delete data for downgrades
12965            flags &= ~PackageManager.DELETE_KEEP_DATA;
12966        } else {
12967            // Preserve data by setting flag
12968            flags |= PackageManager.DELETE_KEEP_DATA;
12969        }
12970        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12971                allUserHandles, perUserInstalled, outInfo, writeSettings);
12972        if (!ret) {
12973            return false;
12974        }
12975        // writer
12976        synchronized (mPackages) {
12977            // Reinstate the old system package
12978            mSettings.enableSystemPackageLPw(newPs.name);
12979            // Remove any native libraries from the upgraded package.
12980            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12981        }
12982        // Install the system package
12983        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12984        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12985        if (locationIsPrivileged(disabledPs.codePath)) {
12986            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12987        }
12988
12989        final PackageParser.Package newPkg;
12990        try {
12991            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12992        } catch (PackageManagerException e) {
12993            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12994            return false;
12995        }
12996
12997        // writer
12998        synchronized (mPackages) {
12999            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13000
13001            // Propagate the permissions state as we do not want to drop on the floor
13002            // runtime permissions. The update permissions method below will take
13003            // care of removing obsolete permissions and grant install permissions.
13004            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13005            updatePermissionsLPw(newPkg.packageName, newPkg,
13006                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13007
13008            if (applyUserRestrictions) {
13009                if (DEBUG_REMOVE) {
13010                    Slog.d(TAG, "Propagating install state across reinstall");
13011                }
13012                for (int i = 0; i < allUserHandles.length; i++) {
13013                    if (DEBUG_REMOVE) {
13014                        Slog.d(TAG, "    user " + allUserHandles[i]
13015                                + " => " + perUserInstalled[i]);
13016                    }
13017                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13018
13019                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13020                }
13021                // Regardless of writeSettings we need to ensure that this restriction
13022                // state propagation is persisted
13023                mSettings.writeAllUsersPackageRestrictionsLPr();
13024            }
13025            // can downgrade to reader here
13026            if (writeSettings) {
13027                mSettings.writeLPr();
13028            }
13029        }
13030        return true;
13031    }
13032
13033    private boolean deleteInstalledPackageLI(PackageSetting ps,
13034            boolean deleteCodeAndResources, int flags,
13035            int[] allUserHandles, boolean[] perUserInstalled,
13036            PackageRemovedInfo outInfo, boolean writeSettings) {
13037        if (outInfo != null) {
13038            outInfo.uid = ps.appId;
13039        }
13040
13041        // Delete package data from internal structures and also remove data if flag is set
13042        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13043
13044        // Delete application code and resources
13045        if (deleteCodeAndResources && (outInfo != null)) {
13046            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13047                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13048            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13049        }
13050        return true;
13051    }
13052
13053    @Override
13054    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13055            int userId) {
13056        mContext.enforceCallingOrSelfPermission(
13057                android.Manifest.permission.DELETE_PACKAGES, null);
13058        synchronized (mPackages) {
13059            PackageSetting ps = mSettings.mPackages.get(packageName);
13060            if (ps == null) {
13061                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13062                return false;
13063            }
13064            if (!ps.getInstalled(userId)) {
13065                // Can't block uninstall for an app that is not installed or enabled.
13066                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13067                return false;
13068            }
13069            ps.setBlockUninstall(blockUninstall, userId);
13070            mSettings.writePackageRestrictionsLPr(userId);
13071        }
13072        return true;
13073    }
13074
13075    @Override
13076    public boolean getBlockUninstallForUser(String packageName, int userId) {
13077        synchronized (mPackages) {
13078            PackageSetting ps = mSettings.mPackages.get(packageName);
13079            if (ps == null) {
13080                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13081                return false;
13082            }
13083            return ps.getBlockUninstall(userId);
13084        }
13085    }
13086
13087    /*
13088     * This method handles package deletion in general
13089     */
13090    private boolean deletePackageLI(String packageName, UserHandle user,
13091            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13092            int flags, PackageRemovedInfo outInfo,
13093            boolean writeSettings) {
13094        if (packageName == null) {
13095            Slog.w(TAG, "Attempt to delete null packageName.");
13096            return false;
13097        }
13098        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13099        PackageSetting ps;
13100        boolean dataOnly = false;
13101        int removeUser = -1;
13102        int appId = -1;
13103        synchronized (mPackages) {
13104            ps = mSettings.mPackages.get(packageName);
13105            if (ps == null) {
13106                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13107                return false;
13108            }
13109            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13110                    && user.getIdentifier() != UserHandle.USER_ALL) {
13111                // The caller is asking that the package only be deleted for a single
13112                // user.  To do this, we just mark its uninstalled state and delete
13113                // its data.  If this is a system app, we only allow this to happen if
13114                // they have set the special DELETE_SYSTEM_APP which requests different
13115                // semantics than normal for uninstalling system apps.
13116                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13117                final int userId = user.getIdentifier();
13118                ps.setUserState(userId,
13119                        COMPONENT_ENABLED_STATE_DEFAULT,
13120                        false, //installed
13121                        true,  //stopped
13122                        true,  //notLaunched
13123                        false, //hidden
13124                        null, null, null,
13125                        false, // blockUninstall
13126                        ps.readUserState(userId).domainVerificationStatus, 0);
13127                if (!isSystemApp(ps)) {
13128                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13129                        // Other user still have this package installed, so all
13130                        // we need to do is clear this user's data and save that
13131                        // it is uninstalled.
13132                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13133                        removeUser = user.getIdentifier();
13134                        appId = ps.appId;
13135                        scheduleWritePackageRestrictionsLocked(removeUser);
13136                    } else {
13137                        // We need to set it back to 'installed' so the uninstall
13138                        // broadcasts will be sent correctly.
13139                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13140                        ps.setInstalled(true, user.getIdentifier());
13141                    }
13142                } else {
13143                    // This is a system app, so we assume that the
13144                    // other users still have this package installed, so all
13145                    // we need to do is clear this user's data and save that
13146                    // it is uninstalled.
13147                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13148                    removeUser = user.getIdentifier();
13149                    appId = ps.appId;
13150                    scheduleWritePackageRestrictionsLocked(removeUser);
13151                }
13152            }
13153        }
13154
13155        if (removeUser >= 0) {
13156            // From above, we determined that we are deleting this only
13157            // for a single user.  Continue the work here.
13158            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13159            if (outInfo != null) {
13160                outInfo.removedPackage = packageName;
13161                outInfo.removedAppId = appId;
13162                outInfo.removedUsers = new int[] {removeUser};
13163            }
13164            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13165            removeKeystoreDataIfNeeded(removeUser, appId);
13166            schedulePackageCleaning(packageName, removeUser, false);
13167            synchronized (mPackages) {
13168                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13169                    scheduleWritePackageRestrictionsLocked(removeUser);
13170                }
13171                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13172            }
13173            return true;
13174        }
13175
13176        if (dataOnly) {
13177            // Delete application data first
13178            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13179            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13180            return true;
13181        }
13182
13183        boolean ret = false;
13184        if (isSystemApp(ps)) {
13185            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13186            // When an updated system application is deleted we delete the existing resources as well and
13187            // fall back to existing code in system partition
13188            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13189                    flags, outInfo, writeSettings);
13190        } else {
13191            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13192            // Kill application pre-emptively especially for apps on sd.
13193            killApplication(packageName, ps.appId, "uninstall pkg");
13194            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13195                    allUserHandles, perUserInstalled,
13196                    outInfo, writeSettings);
13197        }
13198
13199        return ret;
13200    }
13201
13202    private final class ClearStorageConnection implements ServiceConnection {
13203        IMediaContainerService mContainerService;
13204
13205        @Override
13206        public void onServiceConnected(ComponentName name, IBinder service) {
13207            synchronized (this) {
13208                mContainerService = IMediaContainerService.Stub.asInterface(service);
13209                notifyAll();
13210            }
13211        }
13212
13213        @Override
13214        public void onServiceDisconnected(ComponentName name) {
13215        }
13216    }
13217
13218    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13219        final boolean mounted;
13220        if (Environment.isExternalStorageEmulated()) {
13221            mounted = true;
13222        } else {
13223            final String status = Environment.getExternalStorageState();
13224
13225            mounted = status.equals(Environment.MEDIA_MOUNTED)
13226                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13227        }
13228
13229        if (!mounted) {
13230            return;
13231        }
13232
13233        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13234        int[] users;
13235        if (userId == UserHandle.USER_ALL) {
13236            users = sUserManager.getUserIds();
13237        } else {
13238            users = new int[] { userId };
13239        }
13240        final ClearStorageConnection conn = new ClearStorageConnection();
13241        if (mContext.bindServiceAsUser(
13242                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13243            try {
13244                for (int curUser : users) {
13245                    long timeout = SystemClock.uptimeMillis() + 5000;
13246                    synchronized (conn) {
13247                        long now = SystemClock.uptimeMillis();
13248                        while (conn.mContainerService == null && now < timeout) {
13249                            try {
13250                                conn.wait(timeout - now);
13251                            } catch (InterruptedException e) {
13252                            }
13253                        }
13254                    }
13255                    if (conn.mContainerService == null) {
13256                        return;
13257                    }
13258
13259                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13260                    clearDirectory(conn.mContainerService,
13261                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13262                    if (allData) {
13263                        clearDirectory(conn.mContainerService,
13264                                userEnv.buildExternalStorageAppDataDirs(packageName));
13265                        clearDirectory(conn.mContainerService,
13266                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13267                    }
13268                }
13269            } finally {
13270                mContext.unbindService(conn);
13271            }
13272        }
13273    }
13274
13275    @Override
13276    public void clearApplicationUserData(final String packageName,
13277            final IPackageDataObserver observer, final int userId) {
13278        mContext.enforceCallingOrSelfPermission(
13279                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13280        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13281        // Queue up an async operation since the package deletion may take a little while.
13282        mHandler.post(new Runnable() {
13283            public void run() {
13284                mHandler.removeCallbacks(this);
13285                final boolean succeeded;
13286                synchronized (mInstallLock) {
13287                    succeeded = clearApplicationUserDataLI(packageName, userId);
13288                }
13289                clearExternalStorageDataSync(packageName, userId, true);
13290                if (succeeded) {
13291                    // invoke DeviceStorageMonitor's update method to clear any notifications
13292                    DeviceStorageMonitorInternal
13293                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13294                    if (dsm != null) {
13295                        dsm.checkMemory();
13296                    }
13297                }
13298                if(observer != null) {
13299                    try {
13300                        observer.onRemoveCompleted(packageName, succeeded);
13301                    } catch (RemoteException e) {
13302                        Log.i(TAG, "Observer no longer exists.");
13303                    }
13304                } //end if observer
13305            } //end run
13306        });
13307    }
13308
13309    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13310        if (packageName == null) {
13311            Slog.w(TAG, "Attempt to delete null packageName.");
13312            return false;
13313        }
13314
13315        // Try finding details about the requested package
13316        PackageParser.Package pkg;
13317        synchronized (mPackages) {
13318            pkg = mPackages.get(packageName);
13319            if (pkg == null) {
13320                final PackageSetting ps = mSettings.mPackages.get(packageName);
13321                if (ps != null) {
13322                    pkg = ps.pkg;
13323                }
13324            }
13325
13326            if (pkg == null) {
13327                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13328                return false;
13329            }
13330
13331            PackageSetting ps = (PackageSetting) pkg.mExtras;
13332            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13333        }
13334
13335        // Always delete data directories for package, even if we found no other
13336        // record of app. This helps users recover from UID mismatches without
13337        // resorting to a full data wipe.
13338        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13339        if (retCode < 0) {
13340            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13341            return false;
13342        }
13343
13344        final int appId = pkg.applicationInfo.uid;
13345        removeKeystoreDataIfNeeded(userId, appId);
13346
13347        // Create a native library symlink only if we have native libraries
13348        // and if the native libraries are 32 bit libraries. We do not provide
13349        // this symlink for 64 bit libraries.
13350        if (pkg.applicationInfo.primaryCpuAbi != null &&
13351                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13352            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13353            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13354                    nativeLibPath, userId) < 0) {
13355                Slog.w(TAG, "Failed linking native library dir");
13356                return false;
13357            }
13358        }
13359
13360        return true;
13361    }
13362
13363    /**
13364     * Reverts user permission state changes (permissions and flags) in
13365     * all packages for a given user.
13366     *
13367     * @param userId The device user for which to do a reset.
13368     */
13369    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13370        final int packageCount = mPackages.size();
13371        for (int i = 0; i < packageCount; i++) {
13372            PackageParser.Package pkg = mPackages.valueAt(i);
13373            PackageSetting ps = (PackageSetting) pkg.mExtras;
13374            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13375        }
13376    }
13377
13378    /**
13379     * Reverts user permission state changes (permissions and flags).
13380     *
13381     * @param ps The package for which to reset.
13382     * @param userId The device user for which to do a reset.
13383     */
13384    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13385            final PackageSetting ps, final int userId) {
13386        if (ps.pkg == null) {
13387            return;
13388        }
13389
13390        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13391                | FLAG_PERMISSION_USER_FIXED
13392                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13393
13394        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13395                | FLAG_PERMISSION_POLICY_FIXED;
13396
13397        boolean writeInstallPermissions = false;
13398        boolean writeRuntimePermissions = false;
13399
13400        final int permissionCount = ps.pkg.requestedPermissions.size();
13401        for (int i = 0; i < permissionCount; i++) {
13402            String permission = ps.pkg.requestedPermissions.get(i);
13403
13404            BasePermission bp = mSettings.mPermissions.get(permission);
13405            if (bp == null) {
13406                continue;
13407            }
13408
13409            // If shared user we just reset the state to which only this app contributed.
13410            if (ps.sharedUser != null) {
13411                boolean used = false;
13412                final int packageCount = ps.sharedUser.packages.size();
13413                for (int j = 0; j < packageCount; j++) {
13414                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13415                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13416                            && pkg.pkg.requestedPermissions.contains(permission)) {
13417                        used = true;
13418                        break;
13419                    }
13420                }
13421                if (used) {
13422                    continue;
13423                }
13424            }
13425
13426            PermissionsState permissionsState = ps.getPermissionsState();
13427
13428            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13429
13430            // Always clear the user settable flags.
13431            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13432                    bp.name) != null;
13433            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13434                if (hasInstallState) {
13435                    writeInstallPermissions = true;
13436                } else {
13437                    writeRuntimePermissions = true;
13438                }
13439            }
13440
13441            // Below is only runtime permission handling.
13442            if (!bp.isRuntime()) {
13443                continue;
13444            }
13445
13446            // Never clobber system or policy.
13447            if ((oldFlags & policyOrSystemFlags) != 0) {
13448                continue;
13449            }
13450
13451            // If this permission was granted by default, make sure it is.
13452            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13453                if (permissionsState.grantRuntimePermission(bp, userId)
13454                        != PERMISSION_OPERATION_FAILURE) {
13455                    writeRuntimePermissions = true;
13456                }
13457            } else {
13458                // Otherwise, reset the permission.
13459                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13460                switch (revokeResult) {
13461                    case PERMISSION_OPERATION_SUCCESS: {
13462                        writeRuntimePermissions = true;
13463                    } break;
13464
13465                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13466                        writeRuntimePermissions = true;
13467                        final int appId = ps.appId;
13468                        mHandler.post(new Runnable() {
13469                            @Override
13470                            public void run() {
13471                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13472                            }
13473                        });
13474                    } break;
13475                }
13476            }
13477        }
13478
13479        // Synchronously write as we are taking permissions away.
13480        if (writeRuntimePermissions) {
13481            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13482        }
13483
13484        // Synchronously write as we are taking permissions away.
13485        if (writeInstallPermissions) {
13486            mSettings.writeLPr();
13487        }
13488    }
13489
13490    /**
13491     * Remove entries from the keystore daemon. Will only remove it if the
13492     * {@code appId} is valid.
13493     */
13494    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13495        if (appId < 0) {
13496            return;
13497        }
13498
13499        final KeyStore keyStore = KeyStore.getInstance();
13500        if (keyStore != null) {
13501            if (userId == UserHandle.USER_ALL) {
13502                for (final int individual : sUserManager.getUserIds()) {
13503                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13504                }
13505            } else {
13506                keyStore.clearUid(UserHandle.getUid(userId, appId));
13507            }
13508        } else {
13509            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13510        }
13511    }
13512
13513    @Override
13514    public void deleteApplicationCacheFiles(final String packageName,
13515            final IPackageDataObserver observer) {
13516        mContext.enforceCallingOrSelfPermission(
13517                android.Manifest.permission.DELETE_CACHE_FILES, null);
13518        // Queue up an async operation since the package deletion may take a little while.
13519        final int userId = UserHandle.getCallingUserId();
13520        mHandler.post(new Runnable() {
13521            public void run() {
13522                mHandler.removeCallbacks(this);
13523                final boolean succeded;
13524                synchronized (mInstallLock) {
13525                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13526                }
13527                clearExternalStorageDataSync(packageName, userId, false);
13528                if (observer != null) {
13529                    try {
13530                        observer.onRemoveCompleted(packageName, succeded);
13531                    } catch (RemoteException e) {
13532                        Log.i(TAG, "Observer no longer exists.");
13533                    }
13534                } //end if observer
13535            } //end run
13536        });
13537    }
13538
13539    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13540        if (packageName == null) {
13541            Slog.w(TAG, "Attempt to delete null packageName.");
13542            return false;
13543        }
13544        PackageParser.Package p;
13545        synchronized (mPackages) {
13546            p = mPackages.get(packageName);
13547        }
13548        if (p == null) {
13549            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13550            return false;
13551        }
13552        final ApplicationInfo applicationInfo = p.applicationInfo;
13553        if (applicationInfo == null) {
13554            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13555            return false;
13556        }
13557        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13558        if (retCode < 0) {
13559            Slog.w(TAG, "Couldn't remove cache files for package: "
13560                       + packageName + " u" + userId);
13561            return false;
13562        }
13563        return true;
13564    }
13565
13566    @Override
13567    public void getPackageSizeInfo(final String packageName, int userHandle,
13568            final IPackageStatsObserver observer) {
13569        mContext.enforceCallingOrSelfPermission(
13570                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13571        if (packageName == null) {
13572            throw new IllegalArgumentException("Attempt to get size of null packageName");
13573        }
13574
13575        PackageStats stats = new PackageStats(packageName, userHandle);
13576
13577        /*
13578         * Queue up an async operation since the package measurement may take a
13579         * little while.
13580         */
13581        Message msg = mHandler.obtainMessage(INIT_COPY);
13582        msg.obj = new MeasureParams(stats, observer);
13583        mHandler.sendMessage(msg);
13584    }
13585
13586    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13587            PackageStats pStats) {
13588        if (packageName == null) {
13589            Slog.w(TAG, "Attempt to get size of null packageName.");
13590            return false;
13591        }
13592        PackageParser.Package p;
13593        boolean dataOnly = false;
13594        String libDirRoot = null;
13595        String asecPath = null;
13596        PackageSetting ps = null;
13597        synchronized (mPackages) {
13598            p = mPackages.get(packageName);
13599            ps = mSettings.mPackages.get(packageName);
13600            if(p == null) {
13601                dataOnly = true;
13602                if((ps == null) || (ps.pkg == null)) {
13603                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13604                    return false;
13605                }
13606                p = ps.pkg;
13607            }
13608            if (ps != null) {
13609                libDirRoot = ps.legacyNativeLibraryPathString;
13610            }
13611            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13612                final long token = Binder.clearCallingIdentity();
13613                try {
13614                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13615                    if (secureContainerId != null) {
13616                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13617                    }
13618                } finally {
13619                    Binder.restoreCallingIdentity(token);
13620                }
13621            }
13622        }
13623        String publicSrcDir = null;
13624        if(!dataOnly) {
13625            final ApplicationInfo applicationInfo = p.applicationInfo;
13626            if (applicationInfo == null) {
13627                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13628                return false;
13629            }
13630            if (p.isForwardLocked()) {
13631                publicSrcDir = applicationInfo.getBaseResourcePath();
13632            }
13633        }
13634        // TODO: extend to measure size of split APKs
13635        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13636        // not just the first level.
13637        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13638        // just the primary.
13639        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13640
13641        String apkPath;
13642        File packageDir = new File(p.codePath);
13643
13644        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13645            apkPath = packageDir.getAbsolutePath();
13646            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13647            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13648                libDirRoot = null;
13649            }
13650        } else {
13651            apkPath = p.baseCodePath;
13652        }
13653
13654        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13655                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13656        if (res < 0) {
13657            return false;
13658        }
13659
13660        // Fix-up for forward-locked applications in ASEC containers.
13661        if (!isExternal(p)) {
13662            pStats.codeSize += pStats.externalCodeSize;
13663            pStats.externalCodeSize = 0L;
13664        }
13665
13666        return true;
13667    }
13668
13669
13670    @Override
13671    public void addPackageToPreferred(String packageName) {
13672        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13673    }
13674
13675    @Override
13676    public void removePackageFromPreferred(String packageName) {
13677        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13678    }
13679
13680    @Override
13681    public List<PackageInfo> getPreferredPackages(int flags) {
13682        return new ArrayList<PackageInfo>();
13683    }
13684
13685    private int getUidTargetSdkVersionLockedLPr(int uid) {
13686        Object obj = mSettings.getUserIdLPr(uid);
13687        if (obj instanceof SharedUserSetting) {
13688            final SharedUserSetting sus = (SharedUserSetting) obj;
13689            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13690            final Iterator<PackageSetting> it = sus.packages.iterator();
13691            while (it.hasNext()) {
13692                final PackageSetting ps = it.next();
13693                if (ps.pkg != null) {
13694                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13695                    if (v < vers) vers = v;
13696                }
13697            }
13698            return vers;
13699        } else if (obj instanceof PackageSetting) {
13700            final PackageSetting ps = (PackageSetting) obj;
13701            if (ps.pkg != null) {
13702                return ps.pkg.applicationInfo.targetSdkVersion;
13703            }
13704        }
13705        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13706    }
13707
13708    @Override
13709    public void addPreferredActivity(IntentFilter filter, int match,
13710            ComponentName[] set, ComponentName activity, int userId) {
13711        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13712                "Adding preferred");
13713    }
13714
13715    private void addPreferredActivityInternal(IntentFilter filter, int match,
13716            ComponentName[] set, ComponentName activity, boolean always, int userId,
13717            String opname) {
13718        // writer
13719        int callingUid = Binder.getCallingUid();
13720        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13721        if (filter.countActions() == 0) {
13722            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13723            return;
13724        }
13725        synchronized (mPackages) {
13726            if (mContext.checkCallingOrSelfPermission(
13727                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13728                    != PackageManager.PERMISSION_GRANTED) {
13729                if (getUidTargetSdkVersionLockedLPr(callingUid)
13730                        < Build.VERSION_CODES.FROYO) {
13731                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13732                            + callingUid);
13733                    return;
13734                }
13735                mContext.enforceCallingOrSelfPermission(
13736                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13737            }
13738
13739            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13740            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13741                    + userId + ":");
13742            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13743            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13744            scheduleWritePackageRestrictionsLocked(userId);
13745        }
13746    }
13747
13748    @Override
13749    public void replacePreferredActivity(IntentFilter filter, int match,
13750            ComponentName[] set, ComponentName activity, int userId) {
13751        if (filter.countActions() != 1) {
13752            throw new IllegalArgumentException(
13753                    "replacePreferredActivity expects filter to have only 1 action.");
13754        }
13755        if (filter.countDataAuthorities() != 0
13756                || filter.countDataPaths() != 0
13757                || filter.countDataSchemes() > 1
13758                || filter.countDataTypes() != 0) {
13759            throw new IllegalArgumentException(
13760                    "replacePreferredActivity expects filter to have no data authorities, " +
13761                    "paths, or types; and at most one scheme.");
13762        }
13763
13764        final int callingUid = Binder.getCallingUid();
13765        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13766        synchronized (mPackages) {
13767            if (mContext.checkCallingOrSelfPermission(
13768                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13769                    != PackageManager.PERMISSION_GRANTED) {
13770                if (getUidTargetSdkVersionLockedLPr(callingUid)
13771                        < Build.VERSION_CODES.FROYO) {
13772                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13773                            + Binder.getCallingUid());
13774                    return;
13775                }
13776                mContext.enforceCallingOrSelfPermission(
13777                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13778            }
13779
13780            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13781            if (pir != null) {
13782                // Get all of the existing entries that exactly match this filter.
13783                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13784                if (existing != null && existing.size() == 1) {
13785                    PreferredActivity cur = existing.get(0);
13786                    if (DEBUG_PREFERRED) {
13787                        Slog.i(TAG, "Checking replace of preferred:");
13788                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13789                        if (!cur.mPref.mAlways) {
13790                            Slog.i(TAG, "  -- CUR; not mAlways!");
13791                        } else {
13792                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13793                            Slog.i(TAG, "  -- CUR: mSet="
13794                                    + Arrays.toString(cur.mPref.mSetComponents));
13795                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13796                            Slog.i(TAG, "  -- NEW: mMatch="
13797                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13798                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13799                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13800                        }
13801                    }
13802                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13803                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13804                            && cur.mPref.sameSet(set)) {
13805                        // Setting the preferred activity to what it happens to be already
13806                        if (DEBUG_PREFERRED) {
13807                            Slog.i(TAG, "Replacing with same preferred activity "
13808                                    + cur.mPref.mShortComponent + " for user "
13809                                    + userId + ":");
13810                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13811                        }
13812                        return;
13813                    }
13814                }
13815
13816                if (existing != null) {
13817                    if (DEBUG_PREFERRED) {
13818                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13819                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13820                    }
13821                    for (int i = 0; i < existing.size(); i++) {
13822                        PreferredActivity pa = existing.get(i);
13823                        if (DEBUG_PREFERRED) {
13824                            Slog.i(TAG, "Removing existing preferred activity "
13825                                    + pa.mPref.mComponent + ":");
13826                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13827                        }
13828                        pir.removeFilter(pa);
13829                    }
13830                }
13831            }
13832            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13833                    "Replacing preferred");
13834        }
13835    }
13836
13837    @Override
13838    public void clearPackagePreferredActivities(String packageName) {
13839        final int uid = Binder.getCallingUid();
13840        // writer
13841        synchronized (mPackages) {
13842            PackageParser.Package pkg = mPackages.get(packageName);
13843            if (pkg == null || pkg.applicationInfo.uid != uid) {
13844                if (mContext.checkCallingOrSelfPermission(
13845                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13846                        != PackageManager.PERMISSION_GRANTED) {
13847                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13848                            < Build.VERSION_CODES.FROYO) {
13849                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13850                                + Binder.getCallingUid());
13851                        return;
13852                    }
13853                    mContext.enforceCallingOrSelfPermission(
13854                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13855                }
13856            }
13857
13858            int user = UserHandle.getCallingUserId();
13859            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13860                scheduleWritePackageRestrictionsLocked(user);
13861            }
13862        }
13863    }
13864
13865    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13866    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13867        ArrayList<PreferredActivity> removed = null;
13868        boolean changed = false;
13869        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13870            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13871            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13872            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13873                continue;
13874            }
13875            Iterator<PreferredActivity> it = pir.filterIterator();
13876            while (it.hasNext()) {
13877                PreferredActivity pa = it.next();
13878                // Mark entry for removal only if it matches the package name
13879                // and the entry is of type "always".
13880                if (packageName == null ||
13881                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13882                                && pa.mPref.mAlways)) {
13883                    if (removed == null) {
13884                        removed = new ArrayList<PreferredActivity>();
13885                    }
13886                    removed.add(pa);
13887                }
13888            }
13889            if (removed != null) {
13890                for (int j=0; j<removed.size(); j++) {
13891                    PreferredActivity pa = removed.get(j);
13892                    pir.removeFilter(pa);
13893                }
13894                changed = true;
13895            }
13896        }
13897        return changed;
13898    }
13899
13900    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13901    private void clearIntentFilterVerificationsLPw(int userId) {
13902        final int packageCount = mPackages.size();
13903        for (int i = 0; i < packageCount; i++) {
13904            PackageParser.Package pkg = mPackages.valueAt(i);
13905            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13906        }
13907    }
13908
13909    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13910    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13911        if (userId == UserHandle.USER_ALL) {
13912            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13913                    sUserManager.getUserIds())) {
13914                for (int oneUserId : sUserManager.getUserIds()) {
13915                    scheduleWritePackageRestrictionsLocked(oneUserId);
13916                }
13917            }
13918        } else {
13919            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13920                scheduleWritePackageRestrictionsLocked(userId);
13921            }
13922        }
13923    }
13924
13925    void clearDefaultBrowserIfNeeded(String packageName) {
13926        for (int oneUserId : sUserManager.getUserIds()) {
13927            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13928            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13929            if (packageName.equals(defaultBrowserPackageName)) {
13930                setDefaultBrowserPackageName(null, oneUserId);
13931            }
13932        }
13933    }
13934
13935    @Override
13936    public void resetApplicationPreferences(int userId) {
13937        mContext.enforceCallingOrSelfPermission(
13938                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13939        // writer
13940        synchronized (mPackages) {
13941            final long identity = Binder.clearCallingIdentity();
13942            try {
13943                clearPackagePreferredActivitiesLPw(null, userId);
13944                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13945                // TODO: We have to reset the default SMS and Phone. This requires
13946                // significant refactoring to keep all default apps in the package
13947                // manager (cleaner but more work) or have the services provide
13948                // callbacks to the package manager to request a default app reset.
13949                applyFactoryDefaultBrowserLPw(userId);
13950                clearIntentFilterVerificationsLPw(userId);
13951                primeDomainVerificationsLPw(userId);
13952                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13953                scheduleWritePackageRestrictionsLocked(userId);
13954            } finally {
13955                Binder.restoreCallingIdentity(identity);
13956            }
13957        }
13958    }
13959
13960    @Override
13961    public int getPreferredActivities(List<IntentFilter> outFilters,
13962            List<ComponentName> outActivities, String packageName) {
13963
13964        int num = 0;
13965        final int userId = UserHandle.getCallingUserId();
13966        // reader
13967        synchronized (mPackages) {
13968            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13969            if (pir != null) {
13970                final Iterator<PreferredActivity> it = pir.filterIterator();
13971                while (it.hasNext()) {
13972                    final PreferredActivity pa = it.next();
13973                    if (packageName == null
13974                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13975                                    && pa.mPref.mAlways)) {
13976                        if (outFilters != null) {
13977                            outFilters.add(new IntentFilter(pa));
13978                        }
13979                        if (outActivities != null) {
13980                            outActivities.add(pa.mPref.mComponent);
13981                        }
13982                    }
13983                }
13984            }
13985        }
13986
13987        return num;
13988    }
13989
13990    @Override
13991    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13992            int userId) {
13993        int callingUid = Binder.getCallingUid();
13994        if (callingUid != Process.SYSTEM_UID) {
13995            throw new SecurityException(
13996                    "addPersistentPreferredActivity can only be run by the system");
13997        }
13998        if (filter.countActions() == 0) {
13999            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14000            return;
14001        }
14002        synchronized (mPackages) {
14003            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14004                    " :");
14005            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14006            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14007                    new PersistentPreferredActivity(filter, activity));
14008            scheduleWritePackageRestrictionsLocked(userId);
14009        }
14010    }
14011
14012    @Override
14013    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14014        int callingUid = Binder.getCallingUid();
14015        if (callingUid != Process.SYSTEM_UID) {
14016            throw new SecurityException(
14017                    "clearPackagePersistentPreferredActivities can only be run by the system");
14018        }
14019        ArrayList<PersistentPreferredActivity> removed = null;
14020        boolean changed = false;
14021        synchronized (mPackages) {
14022            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14023                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14024                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14025                        .valueAt(i);
14026                if (userId != thisUserId) {
14027                    continue;
14028                }
14029                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14030                while (it.hasNext()) {
14031                    PersistentPreferredActivity ppa = it.next();
14032                    // Mark entry for removal only if it matches the package name.
14033                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14034                        if (removed == null) {
14035                            removed = new ArrayList<PersistentPreferredActivity>();
14036                        }
14037                        removed.add(ppa);
14038                    }
14039                }
14040                if (removed != null) {
14041                    for (int j=0; j<removed.size(); j++) {
14042                        PersistentPreferredActivity ppa = removed.get(j);
14043                        ppir.removeFilter(ppa);
14044                    }
14045                    changed = true;
14046                }
14047            }
14048
14049            if (changed) {
14050                scheduleWritePackageRestrictionsLocked(userId);
14051            }
14052        }
14053    }
14054
14055    /**
14056     * Common machinery for picking apart a restored XML blob and passing
14057     * it to a caller-supplied functor to be applied to the running system.
14058     */
14059    private void restoreFromXml(XmlPullParser parser, int userId,
14060            String expectedStartTag, BlobXmlRestorer functor)
14061            throws IOException, XmlPullParserException {
14062        int type;
14063        while ((type = parser.next()) != XmlPullParser.START_TAG
14064                && type != XmlPullParser.END_DOCUMENT) {
14065        }
14066        if (type != XmlPullParser.START_TAG) {
14067            // oops didn't find a start tag?!
14068            if (DEBUG_BACKUP) {
14069                Slog.e(TAG, "Didn't find start tag during restore");
14070            }
14071            return;
14072        }
14073
14074        // this is supposed to be TAG_PREFERRED_BACKUP
14075        if (!expectedStartTag.equals(parser.getName())) {
14076            if (DEBUG_BACKUP) {
14077                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14078            }
14079            return;
14080        }
14081
14082        // skip interfering stuff, then we're aligned with the backing implementation
14083        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14084        functor.apply(parser, userId);
14085    }
14086
14087    private interface BlobXmlRestorer {
14088        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14089    }
14090
14091    /**
14092     * Non-Binder method, support for the backup/restore mechanism: write the
14093     * full set of preferred activities in its canonical XML format.  Returns the
14094     * XML output as a byte array, or null if there is none.
14095     */
14096    @Override
14097    public byte[] getPreferredActivityBackup(int userId) {
14098        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14099            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14100        }
14101
14102        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14103        try {
14104            final XmlSerializer serializer = new FastXmlSerializer();
14105            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14106            serializer.startDocument(null, true);
14107            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14108
14109            synchronized (mPackages) {
14110                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14111            }
14112
14113            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14114            serializer.endDocument();
14115            serializer.flush();
14116        } catch (Exception e) {
14117            if (DEBUG_BACKUP) {
14118                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14119            }
14120            return null;
14121        }
14122
14123        return dataStream.toByteArray();
14124    }
14125
14126    @Override
14127    public void restorePreferredActivities(byte[] backup, int userId) {
14128        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14129            throw new SecurityException("Only the system may call restorePreferredActivities()");
14130        }
14131
14132        try {
14133            final XmlPullParser parser = Xml.newPullParser();
14134            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14135            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14136                    new BlobXmlRestorer() {
14137                        @Override
14138                        public void apply(XmlPullParser parser, int userId)
14139                                throws XmlPullParserException, IOException {
14140                            synchronized (mPackages) {
14141                                mSettings.readPreferredActivitiesLPw(parser, userId);
14142                            }
14143                        }
14144                    } );
14145        } catch (Exception e) {
14146            if (DEBUG_BACKUP) {
14147                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14148            }
14149        }
14150    }
14151
14152    /**
14153     * Non-Binder method, support for the backup/restore mechanism: write the
14154     * default browser (etc) settings in its canonical XML format.  Returns the default
14155     * browser XML representation as a byte array, or null if there is none.
14156     */
14157    @Override
14158    public byte[] getDefaultAppsBackup(int userId) {
14159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14160            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14161        }
14162
14163        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14164        try {
14165            final XmlSerializer serializer = new FastXmlSerializer();
14166            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14167            serializer.startDocument(null, true);
14168            serializer.startTag(null, TAG_DEFAULT_APPS);
14169
14170            synchronized (mPackages) {
14171                mSettings.writeDefaultAppsLPr(serializer, userId);
14172            }
14173
14174            serializer.endTag(null, TAG_DEFAULT_APPS);
14175            serializer.endDocument();
14176            serializer.flush();
14177        } catch (Exception e) {
14178            if (DEBUG_BACKUP) {
14179                Slog.e(TAG, "Unable to write default apps for backup", e);
14180            }
14181            return null;
14182        }
14183
14184        return dataStream.toByteArray();
14185    }
14186
14187    @Override
14188    public void restoreDefaultApps(byte[] backup, int userId) {
14189        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14190            throw new SecurityException("Only the system may call restoreDefaultApps()");
14191        }
14192
14193        try {
14194            final XmlPullParser parser = Xml.newPullParser();
14195            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14196            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14197                    new BlobXmlRestorer() {
14198                        @Override
14199                        public void apply(XmlPullParser parser, int userId)
14200                                throws XmlPullParserException, IOException {
14201                            synchronized (mPackages) {
14202                                mSettings.readDefaultAppsLPw(parser, userId);
14203                            }
14204                        }
14205                    } );
14206        } catch (Exception e) {
14207            if (DEBUG_BACKUP) {
14208                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14209            }
14210        }
14211    }
14212
14213    @Override
14214    public byte[] getIntentFilterVerificationBackup(int userId) {
14215        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14216            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14217        }
14218
14219        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14220        try {
14221            final XmlSerializer serializer = new FastXmlSerializer();
14222            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14223            serializer.startDocument(null, true);
14224            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14225
14226            synchronized (mPackages) {
14227                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14228            }
14229
14230            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14231            serializer.endDocument();
14232            serializer.flush();
14233        } catch (Exception e) {
14234            if (DEBUG_BACKUP) {
14235                Slog.e(TAG, "Unable to write default apps for backup", e);
14236            }
14237            return null;
14238        }
14239
14240        return dataStream.toByteArray();
14241    }
14242
14243    @Override
14244    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14245        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14246            throw new SecurityException("Only the system may call restorePreferredActivities()");
14247        }
14248
14249        try {
14250            final XmlPullParser parser = Xml.newPullParser();
14251            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14252            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14253                    new BlobXmlRestorer() {
14254                        @Override
14255                        public void apply(XmlPullParser parser, int userId)
14256                                throws XmlPullParserException, IOException {
14257                            synchronized (mPackages) {
14258                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14259                                mSettings.writeLPr();
14260                            }
14261                        }
14262                    } );
14263        } catch (Exception e) {
14264            if (DEBUG_BACKUP) {
14265                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14266            }
14267        }
14268    }
14269
14270    @Override
14271    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14272            int sourceUserId, int targetUserId, int flags) {
14273        mContext.enforceCallingOrSelfPermission(
14274                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14275        int callingUid = Binder.getCallingUid();
14276        enforceOwnerRights(ownerPackage, callingUid);
14277        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14278        if (intentFilter.countActions() == 0) {
14279            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14280            return;
14281        }
14282        synchronized (mPackages) {
14283            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14284                    ownerPackage, targetUserId, flags);
14285            CrossProfileIntentResolver resolver =
14286                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14287            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14288            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14289            if (existing != null) {
14290                int size = existing.size();
14291                for (int i = 0; i < size; i++) {
14292                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14293                        return;
14294                    }
14295                }
14296            }
14297            resolver.addFilter(newFilter);
14298            scheduleWritePackageRestrictionsLocked(sourceUserId);
14299        }
14300    }
14301
14302    @Override
14303    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14304        mContext.enforceCallingOrSelfPermission(
14305                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14306        int callingUid = Binder.getCallingUid();
14307        enforceOwnerRights(ownerPackage, callingUid);
14308        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14309        synchronized (mPackages) {
14310            CrossProfileIntentResolver resolver =
14311                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14312            ArraySet<CrossProfileIntentFilter> set =
14313                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14314            for (CrossProfileIntentFilter filter : set) {
14315                if (filter.getOwnerPackage().equals(ownerPackage)) {
14316                    resolver.removeFilter(filter);
14317                }
14318            }
14319            scheduleWritePackageRestrictionsLocked(sourceUserId);
14320        }
14321    }
14322
14323    // Enforcing that callingUid is owning pkg on userId
14324    private void enforceOwnerRights(String pkg, int callingUid) {
14325        // The system owns everything.
14326        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14327            return;
14328        }
14329        int callingUserId = UserHandle.getUserId(callingUid);
14330        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14331        if (pi == null) {
14332            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14333                    + callingUserId);
14334        }
14335        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14336            throw new SecurityException("Calling uid " + callingUid
14337                    + " does not own package " + pkg);
14338        }
14339    }
14340
14341    @Override
14342    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14343        Intent intent = new Intent(Intent.ACTION_MAIN);
14344        intent.addCategory(Intent.CATEGORY_HOME);
14345
14346        final int callingUserId = UserHandle.getCallingUserId();
14347        List<ResolveInfo> list = queryIntentActivities(intent, null,
14348                PackageManager.GET_META_DATA, callingUserId);
14349        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14350                true, false, false, callingUserId);
14351
14352        allHomeCandidates.clear();
14353        if (list != null) {
14354            for (ResolveInfo ri : list) {
14355                allHomeCandidates.add(ri);
14356            }
14357        }
14358        return (preferred == null || preferred.activityInfo == null)
14359                ? null
14360                : new ComponentName(preferred.activityInfo.packageName,
14361                        preferred.activityInfo.name);
14362    }
14363
14364    @Override
14365    public void setApplicationEnabledSetting(String appPackageName,
14366            int newState, int flags, int userId, String callingPackage) {
14367        if (!sUserManager.exists(userId)) return;
14368        if (callingPackage == null) {
14369            callingPackage = Integer.toString(Binder.getCallingUid());
14370        }
14371        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14372    }
14373
14374    @Override
14375    public void setComponentEnabledSetting(ComponentName componentName,
14376            int newState, int flags, int userId) {
14377        if (!sUserManager.exists(userId)) return;
14378        setEnabledSetting(componentName.getPackageName(),
14379                componentName.getClassName(), newState, flags, userId, null);
14380    }
14381
14382    private void setEnabledSetting(final String packageName, String className, int newState,
14383            final int flags, int userId, String callingPackage) {
14384        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14385              || newState == COMPONENT_ENABLED_STATE_ENABLED
14386              || newState == COMPONENT_ENABLED_STATE_DISABLED
14387              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14388              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14389            throw new IllegalArgumentException("Invalid new component state: "
14390                    + newState);
14391        }
14392        PackageSetting pkgSetting;
14393        final int uid = Binder.getCallingUid();
14394        final int permission = mContext.checkCallingOrSelfPermission(
14395                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14396        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14397        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14398        boolean sendNow = false;
14399        boolean isApp = (className == null);
14400        String componentName = isApp ? packageName : className;
14401        int packageUid = -1;
14402        ArrayList<String> components;
14403
14404        // writer
14405        synchronized (mPackages) {
14406            pkgSetting = mSettings.mPackages.get(packageName);
14407            if (pkgSetting == null) {
14408                if (className == null) {
14409                    throw new IllegalArgumentException(
14410                            "Unknown package: " + packageName);
14411                }
14412                throw new IllegalArgumentException(
14413                        "Unknown component: " + packageName
14414                        + "/" + className);
14415            }
14416            // Allow root and verify that userId is not being specified by a different user
14417            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14418                throw new SecurityException(
14419                        "Permission Denial: attempt to change component state from pid="
14420                        + Binder.getCallingPid()
14421                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14422            }
14423            if (className == null) {
14424                // We're dealing with an application/package level state change
14425                if (pkgSetting.getEnabled(userId) == newState) {
14426                    // Nothing to do
14427                    return;
14428                }
14429                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14430                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14431                    // Don't care about who enables an app.
14432                    callingPackage = null;
14433                }
14434                pkgSetting.setEnabled(newState, userId, callingPackage);
14435                // pkgSetting.pkg.mSetEnabled = newState;
14436            } else {
14437                // We're dealing with a component level state change
14438                // First, verify that this is a valid class name.
14439                PackageParser.Package pkg = pkgSetting.pkg;
14440                if (pkg == null || !pkg.hasComponentClassName(className)) {
14441                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14442                        throw new IllegalArgumentException("Component class " + className
14443                                + " does not exist in " + packageName);
14444                    } else {
14445                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14446                                + className + " does not exist in " + packageName);
14447                    }
14448                }
14449                switch (newState) {
14450                case COMPONENT_ENABLED_STATE_ENABLED:
14451                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14452                        return;
14453                    }
14454                    break;
14455                case COMPONENT_ENABLED_STATE_DISABLED:
14456                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14457                        return;
14458                    }
14459                    break;
14460                case COMPONENT_ENABLED_STATE_DEFAULT:
14461                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14462                        return;
14463                    }
14464                    break;
14465                default:
14466                    Slog.e(TAG, "Invalid new component state: " + newState);
14467                    return;
14468                }
14469            }
14470            scheduleWritePackageRestrictionsLocked(userId);
14471            components = mPendingBroadcasts.get(userId, packageName);
14472            final boolean newPackage = components == null;
14473            if (newPackage) {
14474                components = new ArrayList<String>();
14475            }
14476            if (!components.contains(componentName)) {
14477                components.add(componentName);
14478            }
14479            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14480                sendNow = true;
14481                // Purge entry from pending broadcast list if another one exists already
14482                // since we are sending one right away.
14483                mPendingBroadcasts.remove(userId, packageName);
14484            } else {
14485                if (newPackage) {
14486                    mPendingBroadcasts.put(userId, packageName, components);
14487                }
14488                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14489                    // Schedule a message
14490                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14491                }
14492            }
14493        }
14494
14495        long callingId = Binder.clearCallingIdentity();
14496        try {
14497            if (sendNow) {
14498                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14499                sendPackageChangedBroadcast(packageName,
14500                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14501            }
14502        } finally {
14503            Binder.restoreCallingIdentity(callingId);
14504        }
14505    }
14506
14507    private void sendPackageChangedBroadcast(String packageName,
14508            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14509        if (DEBUG_INSTALL)
14510            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14511                    + componentNames);
14512        Bundle extras = new Bundle(4);
14513        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14514        String nameList[] = new String[componentNames.size()];
14515        componentNames.toArray(nameList);
14516        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14517        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14518        extras.putInt(Intent.EXTRA_UID, packageUid);
14519        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14520                new int[] {UserHandle.getUserId(packageUid)});
14521    }
14522
14523    @Override
14524    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14525        if (!sUserManager.exists(userId)) return;
14526        final int uid = Binder.getCallingUid();
14527        final int permission = mContext.checkCallingOrSelfPermission(
14528                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14529        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14530        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14531        // writer
14532        synchronized (mPackages) {
14533            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14534                    allowedByPermission, uid, userId)) {
14535                scheduleWritePackageRestrictionsLocked(userId);
14536            }
14537        }
14538    }
14539
14540    @Override
14541    public String getInstallerPackageName(String packageName) {
14542        // reader
14543        synchronized (mPackages) {
14544            return mSettings.getInstallerPackageNameLPr(packageName);
14545        }
14546    }
14547
14548    @Override
14549    public int getApplicationEnabledSetting(String packageName, int userId) {
14550        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14551        int uid = Binder.getCallingUid();
14552        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14553        // reader
14554        synchronized (mPackages) {
14555            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14556        }
14557    }
14558
14559    @Override
14560    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14561        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14562        int uid = Binder.getCallingUid();
14563        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14564        // reader
14565        synchronized (mPackages) {
14566            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14567        }
14568    }
14569
14570    @Override
14571    public void enterSafeMode() {
14572        enforceSystemOrRoot("Only the system can request entering safe mode");
14573
14574        if (!mSystemReady) {
14575            mSafeMode = true;
14576        }
14577    }
14578
14579    @Override
14580    public void systemReady() {
14581        mSystemReady = true;
14582
14583        // Read the compatibilty setting when the system is ready.
14584        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14585                mContext.getContentResolver(),
14586                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14587        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14588        if (DEBUG_SETTINGS) {
14589            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14590        }
14591
14592        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14593
14594        synchronized (mPackages) {
14595            // Verify that all of the preferred activity components actually
14596            // exist.  It is possible for applications to be updated and at
14597            // that point remove a previously declared activity component that
14598            // had been set as a preferred activity.  We try to clean this up
14599            // the next time we encounter that preferred activity, but it is
14600            // possible for the user flow to never be able to return to that
14601            // situation so here we do a sanity check to make sure we haven't
14602            // left any junk around.
14603            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14604            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14605                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14606                removed.clear();
14607                for (PreferredActivity pa : pir.filterSet()) {
14608                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14609                        removed.add(pa);
14610                    }
14611                }
14612                if (removed.size() > 0) {
14613                    for (int r=0; r<removed.size(); r++) {
14614                        PreferredActivity pa = removed.get(r);
14615                        Slog.w(TAG, "Removing dangling preferred activity: "
14616                                + pa.mPref.mComponent);
14617                        pir.removeFilter(pa);
14618                    }
14619                    mSettings.writePackageRestrictionsLPr(
14620                            mSettings.mPreferredActivities.keyAt(i));
14621                }
14622            }
14623
14624            for (int userId : UserManagerService.getInstance().getUserIds()) {
14625                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14626                    grantPermissionsUserIds = ArrayUtils.appendInt(
14627                            grantPermissionsUserIds, userId);
14628                }
14629            }
14630        }
14631        sUserManager.systemReady();
14632
14633        // If we upgraded grant all default permissions before kicking off.
14634        for (int userId : grantPermissionsUserIds) {
14635            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14636        }
14637
14638        // Kick off any messages waiting for system ready
14639        if (mPostSystemReadyMessages != null) {
14640            for (Message msg : mPostSystemReadyMessages) {
14641                msg.sendToTarget();
14642            }
14643            mPostSystemReadyMessages = null;
14644        }
14645
14646        // Watch for external volumes that come and go over time
14647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14648        storage.registerListener(mStorageListener);
14649
14650        mInstallerService.systemReady();
14651        mPackageDexOptimizer.systemReady();
14652
14653        MountServiceInternal mountServiceInternal = LocalServices.getService(
14654                MountServiceInternal.class);
14655        mountServiceInternal.addExternalStoragePolicy(
14656                new MountServiceInternal.ExternalStorageMountPolicy() {
14657            @Override
14658            public int getMountMode(int uid, String packageName) {
14659                if (Process.isIsolated(uid)) {
14660                    return Zygote.MOUNT_EXTERNAL_NONE;
14661                }
14662                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14663                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14664                }
14665                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14666                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14667                }
14668                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14669                    return Zygote.MOUNT_EXTERNAL_READ;
14670                }
14671                return Zygote.MOUNT_EXTERNAL_WRITE;
14672            }
14673
14674            @Override
14675            public boolean hasExternalStorage(int uid, String packageName) {
14676                return true;
14677            }
14678        });
14679    }
14680
14681    @Override
14682    public boolean isSafeMode() {
14683        return mSafeMode;
14684    }
14685
14686    @Override
14687    public boolean hasSystemUidErrors() {
14688        return mHasSystemUidErrors;
14689    }
14690
14691    static String arrayToString(int[] array) {
14692        StringBuffer buf = new StringBuffer(128);
14693        buf.append('[');
14694        if (array != null) {
14695            for (int i=0; i<array.length; i++) {
14696                if (i > 0) buf.append(", ");
14697                buf.append(array[i]);
14698            }
14699        }
14700        buf.append(']');
14701        return buf.toString();
14702    }
14703
14704    static class DumpState {
14705        public static final int DUMP_LIBS = 1 << 0;
14706        public static final int DUMP_FEATURES = 1 << 1;
14707        public static final int DUMP_RESOLVERS = 1 << 2;
14708        public static final int DUMP_PERMISSIONS = 1 << 3;
14709        public static final int DUMP_PACKAGES = 1 << 4;
14710        public static final int DUMP_SHARED_USERS = 1 << 5;
14711        public static final int DUMP_MESSAGES = 1 << 6;
14712        public static final int DUMP_PROVIDERS = 1 << 7;
14713        public static final int DUMP_VERIFIERS = 1 << 8;
14714        public static final int DUMP_PREFERRED = 1 << 9;
14715        public static final int DUMP_PREFERRED_XML = 1 << 10;
14716        public static final int DUMP_KEYSETS = 1 << 11;
14717        public static final int DUMP_VERSION = 1 << 12;
14718        public static final int DUMP_INSTALLS = 1 << 13;
14719        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14720        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14721
14722        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14723
14724        private int mTypes;
14725
14726        private int mOptions;
14727
14728        private boolean mTitlePrinted;
14729
14730        private SharedUserSetting mSharedUser;
14731
14732        public boolean isDumping(int type) {
14733            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14734                return true;
14735            }
14736
14737            return (mTypes & type) != 0;
14738        }
14739
14740        public void setDump(int type) {
14741            mTypes |= type;
14742        }
14743
14744        public boolean isOptionEnabled(int option) {
14745            return (mOptions & option) != 0;
14746        }
14747
14748        public void setOptionEnabled(int option) {
14749            mOptions |= option;
14750        }
14751
14752        public boolean onTitlePrinted() {
14753            final boolean printed = mTitlePrinted;
14754            mTitlePrinted = true;
14755            return printed;
14756        }
14757
14758        public boolean getTitlePrinted() {
14759            return mTitlePrinted;
14760        }
14761
14762        public void setTitlePrinted(boolean enabled) {
14763            mTitlePrinted = enabled;
14764        }
14765
14766        public SharedUserSetting getSharedUser() {
14767            return mSharedUser;
14768        }
14769
14770        public void setSharedUser(SharedUserSetting user) {
14771            mSharedUser = user;
14772        }
14773    }
14774
14775    @Override
14776    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14777        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14778                != PackageManager.PERMISSION_GRANTED) {
14779            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14780                    + Binder.getCallingPid()
14781                    + ", uid=" + Binder.getCallingUid()
14782                    + " without permission "
14783                    + android.Manifest.permission.DUMP);
14784            return;
14785        }
14786
14787        DumpState dumpState = new DumpState();
14788        boolean fullPreferred = false;
14789        boolean checkin = false;
14790
14791        String packageName = null;
14792        ArraySet<String> permissionNames = null;
14793
14794        int opti = 0;
14795        while (opti < args.length) {
14796            String opt = args[opti];
14797            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14798                break;
14799            }
14800            opti++;
14801
14802            if ("-a".equals(opt)) {
14803                // Right now we only know how to print all.
14804            } else if ("-h".equals(opt)) {
14805                pw.println("Package manager dump options:");
14806                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14807                pw.println("    --checkin: dump for a checkin");
14808                pw.println("    -f: print details of intent filters");
14809                pw.println("    -h: print this help");
14810                pw.println("  cmd may be one of:");
14811                pw.println("    l[ibraries]: list known shared libraries");
14812                pw.println("    f[ibraries]: list device features");
14813                pw.println("    k[eysets]: print known keysets");
14814                pw.println("    r[esolvers]: dump intent resolvers");
14815                pw.println("    perm[issions]: dump permissions");
14816                pw.println("    permission [name ...]: dump declaration and use of given permission");
14817                pw.println("    pref[erred]: print preferred package settings");
14818                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14819                pw.println("    prov[iders]: dump content providers");
14820                pw.println("    p[ackages]: dump installed packages");
14821                pw.println("    s[hared-users]: dump shared user IDs");
14822                pw.println("    m[essages]: print collected runtime messages");
14823                pw.println("    v[erifiers]: print package verifier info");
14824                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14825                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14826                pw.println("    version: print database version info");
14827                pw.println("    write: write current settings now");
14828                pw.println("    installs: details about install sessions");
14829                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14830                pw.println("    <package.name>: info about given package");
14831                return;
14832            } else if ("--checkin".equals(opt)) {
14833                checkin = true;
14834            } else if ("-f".equals(opt)) {
14835                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14836            } else {
14837                pw.println("Unknown argument: " + opt + "; use -h for help");
14838            }
14839        }
14840
14841        // Is the caller requesting to dump a particular piece of data?
14842        if (opti < args.length) {
14843            String cmd = args[opti];
14844            opti++;
14845            // Is this a package name?
14846            if ("android".equals(cmd) || cmd.contains(".")) {
14847                packageName = cmd;
14848                // When dumping a single package, we always dump all of its
14849                // filter information since the amount of data will be reasonable.
14850                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14851            } else if ("check-permission".equals(cmd)) {
14852                if (opti >= args.length) {
14853                    pw.println("Error: check-permission missing permission argument");
14854                    return;
14855                }
14856                String perm = args[opti];
14857                opti++;
14858                if (opti >= args.length) {
14859                    pw.println("Error: check-permission missing package argument");
14860                    return;
14861                }
14862                String pkg = args[opti];
14863                opti++;
14864                int user = UserHandle.getUserId(Binder.getCallingUid());
14865                if (opti < args.length) {
14866                    try {
14867                        user = Integer.parseInt(args[opti]);
14868                    } catch (NumberFormatException e) {
14869                        pw.println("Error: check-permission user argument is not a number: "
14870                                + args[opti]);
14871                        return;
14872                    }
14873                }
14874                pw.println(checkPermission(perm, pkg, user));
14875                return;
14876            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14877                dumpState.setDump(DumpState.DUMP_LIBS);
14878            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14879                dumpState.setDump(DumpState.DUMP_FEATURES);
14880            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14881                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14882            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14883                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14884            } else if ("permission".equals(cmd)) {
14885                if (opti >= args.length) {
14886                    pw.println("Error: permission requires permission name");
14887                    return;
14888                }
14889                permissionNames = new ArraySet<>();
14890                while (opti < args.length) {
14891                    permissionNames.add(args[opti]);
14892                    opti++;
14893                }
14894                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14895                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14896            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14897                dumpState.setDump(DumpState.DUMP_PREFERRED);
14898            } else if ("preferred-xml".equals(cmd)) {
14899                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14900                if (opti < args.length && "--full".equals(args[opti])) {
14901                    fullPreferred = true;
14902                    opti++;
14903                }
14904            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14905                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14906            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14907                dumpState.setDump(DumpState.DUMP_PACKAGES);
14908            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14909                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14910            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14911                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14912            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14913                dumpState.setDump(DumpState.DUMP_MESSAGES);
14914            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14915                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14916            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14917                    || "intent-filter-verifiers".equals(cmd)) {
14918                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14919            } else if ("version".equals(cmd)) {
14920                dumpState.setDump(DumpState.DUMP_VERSION);
14921            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14922                dumpState.setDump(DumpState.DUMP_KEYSETS);
14923            } else if ("installs".equals(cmd)) {
14924                dumpState.setDump(DumpState.DUMP_INSTALLS);
14925            } else if ("write".equals(cmd)) {
14926                synchronized (mPackages) {
14927                    mSettings.writeLPr();
14928                    pw.println("Settings written.");
14929                    return;
14930                }
14931            }
14932        }
14933
14934        if (checkin) {
14935            pw.println("vers,1");
14936        }
14937
14938        // reader
14939        synchronized (mPackages) {
14940            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14941                if (!checkin) {
14942                    if (dumpState.onTitlePrinted())
14943                        pw.println();
14944                    pw.println("Database versions:");
14945                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14946                }
14947            }
14948
14949            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14950                if (!checkin) {
14951                    if (dumpState.onTitlePrinted())
14952                        pw.println();
14953                    pw.println("Verifiers:");
14954                    pw.print("  Required: ");
14955                    pw.print(mRequiredVerifierPackage);
14956                    pw.print(" (uid=");
14957                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14958                    pw.println(")");
14959                } else if (mRequiredVerifierPackage != null) {
14960                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14961                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14962                }
14963            }
14964
14965            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14966                    packageName == null) {
14967                if (mIntentFilterVerifierComponent != null) {
14968                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14969                    if (!checkin) {
14970                        if (dumpState.onTitlePrinted())
14971                            pw.println();
14972                        pw.println("Intent Filter Verifier:");
14973                        pw.print("  Using: ");
14974                        pw.print(verifierPackageName);
14975                        pw.print(" (uid=");
14976                        pw.print(getPackageUid(verifierPackageName, 0));
14977                        pw.println(")");
14978                    } else if (verifierPackageName != null) {
14979                        pw.print("ifv,"); pw.print(verifierPackageName);
14980                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14981                    }
14982                } else {
14983                    pw.println();
14984                    pw.println("No Intent Filter Verifier available!");
14985                }
14986            }
14987
14988            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14989                boolean printedHeader = false;
14990                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14991                while (it.hasNext()) {
14992                    String name = it.next();
14993                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14994                    if (!checkin) {
14995                        if (!printedHeader) {
14996                            if (dumpState.onTitlePrinted())
14997                                pw.println();
14998                            pw.println("Libraries:");
14999                            printedHeader = true;
15000                        }
15001                        pw.print("  ");
15002                    } else {
15003                        pw.print("lib,");
15004                    }
15005                    pw.print(name);
15006                    if (!checkin) {
15007                        pw.print(" -> ");
15008                    }
15009                    if (ent.path != null) {
15010                        if (!checkin) {
15011                            pw.print("(jar) ");
15012                            pw.print(ent.path);
15013                        } else {
15014                            pw.print(",jar,");
15015                            pw.print(ent.path);
15016                        }
15017                    } else {
15018                        if (!checkin) {
15019                            pw.print("(apk) ");
15020                            pw.print(ent.apk);
15021                        } else {
15022                            pw.print(",apk,");
15023                            pw.print(ent.apk);
15024                        }
15025                    }
15026                    pw.println();
15027                }
15028            }
15029
15030            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15031                if (dumpState.onTitlePrinted())
15032                    pw.println();
15033                if (!checkin) {
15034                    pw.println("Features:");
15035                }
15036                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15037                while (it.hasNext()) {
15038                    String name = it.next();
15039                    if (!checkin) {
15040                        pw.print("  ");
15041                    } else {
15042                        pw.print("feat,");
15043                    }
15044                    pw.println(name);
15045                }
15046            }
15047
15048            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15049                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15050                        : "Activity Resolver Table:", "  ", packageName,
15051                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15052                    dumpState.setTitlePrinted(true);
15053                }
15054                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15055                        : "Receiver Resolver Table:", "  ", packageName,
15056                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15057                    dumpState.setTitlePrinted(true);
15058                }
15059                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15060                        : "Service Resolver Table:", "  ", packageName,
15061                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15062                    dumpState.setTitlePrinted(true);
15063                }
15064                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15065                        : "Provider Resolver Table:", "  ", packageName,
15066                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15067                    dumpState.setTitlePrinted(true);
15068                }
15069            }
15070
15071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15072                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15073                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15074                    int user = mSettings.mPreferredActivities.keyAt(i);
15075                    if (pir.dump(pw,
15076                            dumpState.getTitlePrinted()
15077                                ? "\nPreferred Activities User " + user + ":"
15078                                : "Preferred Activities User " + user + ":", "  ",
15079                            packageName, true, false)) {
15080                        dumpState.setTitlePrinted(true);
15081                    }
15082                }
15083            }
15084
15085            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15086                pw.flush();
15087                FileOutputStream fout = new FileOutputStream(fd);
15088                BufferedOutputStream str = new BufferedOutputStream(fout);
15089                XmlSerializer serializer = new FastXmlSerializer();
15090                try {
15091                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15092                    serializer.startDocument(null, true);
15093                    serializer.setFeature(
15094                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15095                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15096                    serializer.endDocument();
15097                    serializer.flush();
15098                } catch (IllegalArgumentException e) {
15099                    pw.println("Failed writing: " + e);
15100                } catch (IllegalStateException e) {
15101                    pw.println("Failed writing: " + e);
15102                } catch (IOException e) {
15103                    pw.println("Failed writing: " + e);
15104                }
15105            }
15106
15107            if (!checkin
15108                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15109                    && packageName == null) {
15110                pw.println();
15111                int count = mSettings.mPackages.size();
15112                if (count == 0) {
15113                    pw.println("No applications!");
15114                    pw.println();
15115                } else {
15116                    final String prefix = "  ";
15117                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15118                    if (allPackageSettings.size() == 0) {
15119                        pw.println("No domain preferred apps!");
15120                        pw.println();
15121                    } else {
15122                        pw.println("App verification status:");
15123                        pw.println();
15124                        count = 0;
15125                        for (PackageSetting ps : allPackageSettings) {
15126                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15127                            if (ivi == null || ivi.getPackageName() == null) continue;
15128                            pw.println(prefix + "Package: " + ivi.getPackageName());
15129                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15130                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15131                            pw.println();
15132                            count++;
15133                        }
15134                        if (count == 0) {
15135                            pw.println(prefix + "No app verification established.");
15136                            pw.println();
15137                        }
15138                        for (int userId : sUserManager.getUserIds()) {
15139                            pw.println("App linkages for user " + userId + ":");
15140                            pw.println();
15141                            count = 0;
15142                            for (PackageSetting ps : allPackageSettings) {
15143                                final long status = ps.getDomainVerificationStatusForUser(userId);
15144                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15145                                    continue;
15146                                }
15147                                pw.println(prefix + "Package: " + ps.name);
15148                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15149                                String statusStr = IntentFilterVerificationInfo.
15150                                        getStatusStringFromValue(status);
15151                                pw.println(prefix + "Status:  " + statusStr);
15152                                pw.println();
15153                                count++;
15154                            }
15155                            if (count == 0) {
15156                                pw.println(prefix + "No configured app linkages.");
15157                                pw.println();
15158                            }
15159                        }
15160                    }
15161                }
15162            }
15163
15164            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15165                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15166                if (packageName == null && permissionNames == null) {
15167                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15168                        if (iperm == 0) {
15169                            if (dumpState.onTitlePrinted())
15170                                pw.println();
15171                            pw.println("AppOp Permissions:");
15172                        }
15173                        pw.print("  AppOp Permission ");
15174                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15175                        pw.println(":");
15176                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15177                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15178                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15179                        }
15180                    }
15181                }
15182            }
15183
15184            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15185                boolean printedSomething = false;
15186                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15187                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15188                        continue;
15189                    }
15190                    if (!printedSomething) {
15191                        if (dumpState.onTitlePrinted())
15192                            pw.println();
15193                        pw.println("Registered ContentProviders:");
15194                        printedSomething = true;
15195                    }
15196                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15197                    pw.print("    "); pw.println(p.toString());
15198                }
15199                printedSomething = false;
15200                for (Map.Entry<String, PackageParser.Provider> entry :
15201                        mProvidersByAuthority.entrySet()) {
15202                    PackageParser.Provider p = entry.getValue();
15203                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15204                        continue;
15205                    }
15206                    if (!printedSomething) {
15207                        if (dumpState.onTitlePrinted())
15208                            pw.println();
15209                        pw.println("ContentProvider Authorities:");
15210                        printedSomething = true;
15211                    }
15212                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15213                    pw.print("    "); pw.println(p.toString());
15214                    if (p.info != null && p.info.applicationInfo != null) {
15215                        final String appInfo = p.info.applicationInfo.toString();
15216                        pw.print("      applicationInfo="); pw.println(appInfo);
15217                    }
15218                }
15219            }
15220
15221            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15222                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15223            }
15224
15225            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15226                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15227            }
15228
15229            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15230                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15231            }
15232
15233            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15234                // XXX should handle packageName != null by dumping only install data that
15235                // the given package is involved with.
15236                if (dumpState.onTitlePrinted()) pw.println();
15237                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15238            }
15239
15240            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15241                if (dumpState.onTitlePrinted()) pw.println();
15242                mSettings.dumpReadMessagesLPr(pw, dumpState);
15243
15244                pw.println();
15245                pw.println("Package warning messages:");
15246                BufferedReader in = null;
15247                String line = null;
15248                try {
15249                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15250                    while ((line = in.readLine()) != null) {
15251                        if (line.contains("ignored: updated version")) continue;
15252                        pw.println(line);
15253                    }
15254                } catch (IOException ignored) {
15255                } finally {
15256                    IoUtils.closeQuietly(in);
15257                }
15258            }
15259
15260            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15261                BufferedReader in = null;
15262                String line = null;
15263                try {
15264                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15265                    while ((line = in.readLine()) != null) {
15266                        if (line.contains("ignored: updated version")) continue;
15267                        pw.print("msg,");
15268                        pw.println(line);
15269                    }
15270                } catch (IOException ignored) {
15271                } finally {
15272                    IoUtils.closeQuietly(in);
15273                }
15274            }
15275        }
15276    }
15277
15278    private String dumpDomainString(String packageName) {
15279        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15280        List<IntentFilter> filters = getAllIntentFilters(packageName);
15281
15282        ArraySet<String> result = new ArraySet<>();
15283        if (iviList.size() > 0) {
15284            for (IntentFilterVerificationInfo ivi : iviList) {
15285                for (String host : ivi.getDomains()) {
15286                    result.add(host);
15287                }
15288            }
15289        }
15290        if (filters != null && filters.size() > 0) {
15291            for (IntentFilter filter : filters) {
15292                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15293                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15294                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15295                    result.addAll(filter.getHostsList());
15296                }
15297            }
15298        }
15299
15300        StringBuilder sb = new StringBuilder(result.size() * 16);
15301        for (String domain : result) {
15302            if (sb.length() > 0) sb.append(" ");
15303            sb.append(domain);
15304        }
15305        return sb.toString();
15306    }
15307
15308    // ------- apps on sdcard specific code -------
15309    static final boolean DEBUG_SD_INSTALL = false;
15310
15311    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15312
15313    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15314
15315    private boolean mMediaMounted = false;
15316
15317    static String getEncryptKey() {
15318        try {
15319            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15320                    SD_ENCRYPTION_KEYSTORE_NAME);
15321            if (sdEncKey == null) {
15322                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15323                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15324                if (sdEncKey == null) {
15325                    Slog.e(TAG, "Failed to create encryption keys");
15326                    return null;
15327                }
15328            }
15329            return sdEncKey;
15330        } catch (NoSuchAlgorithmException nsae) {
15331            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15332            return null;
15333        } catch (IOException ioe) {
15334            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15335            return null;
15336        }
15337    }
15338
15339    /*
15340     * Update media status on PackageManager.
15341     */
15342    @Override
15343    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15344        int callingUid = Binder.getCallingUid();
15345        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15346            throw new SecurityException("Media status can only be updated by the system");
15347        }
15348        // reader; this apparently protects mMediaMounted, but should probably
15349        // be a different lock in that case.
15350        synchronized (mPackages) {
15351            Log.i(TAG, "Updating external media status from "
15352                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15353                    + (mediaStatus ? "mounted" : "unmounted"));
15354            if (DEBUG_SD_INSTALL)
15355                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15356                        + ", mMediaMounted=" + mMediaMounted);
15357            if (mediaStatus == mMediaMounted) {
15358                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15359                        : 0, -1);
15360                mHandler.sendMessage(msg);
15361                return;
15362            }
15363            mMediaMounted = mediaStatus;
15364        }
15365        // Queue up an async operation since the package installation may take a
15366        // little while.
15367        mHandler.post(new Runnable() {
15368            public void run() {
15369                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15370            }
15371        });
15372    }
15373
15374    /**
15375     * Called by MountService when the initial ASECs to scan are available.
15376     * Should block until all the ASEC containers are finished being scanned.
15377     */
15378    public void scanAvailableAsecs() {
15379        updateExternalMediaStatusInner(true, false, false);
15380        if (mShouldRestoreconData) {
15381            SELinuxMMAC.setRestoreconDone();
15382            mShouldRestoreconData = false;
15383        }
15384    }
15385
15386    /*
15387     * Collect information of applications on external media, map them against
15388     * existing containers and update information based on current mount status.
15389     * Please note that we always have to report status if reportStatus has been
15390     * set to true especially when unloading packages.
15391     */
15392    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15393            boolean externalStorage) {
15394        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15395        int[] uidArr = EmptyArray.INT;
15396
15397        final String[] list = PackageHelper.getSecureContainerList();
15398        if (ArrayUtils.isEmpty(list)) {
15399            Log.i(TAG, "No secure containers found");
15400        } else {
15401            // Process list of secure containers and categorize them
15402            // as active or stale based on their package internal state.
15403
15404            // reader
15405            synchronized (mPackages) {
15406                for (String cid : list) {
15407                    // Leave stages untouched for now; installer service owns them
15408                    if (PackageInstallerService.isStageName(cid)) continue;
15409
15410                    if (DEBUG_SD_INSTALL)
15411                        Log.i(TAG, "Processing container " + cid);
15412                    String pkgName = getAsecPackageName(cid);
15413                    if (pkgName == null) {
15414                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15415                        continue;
15416                    }
15417                    if (DEBUG_SD_INSTALL)
15418                        Log.i(TAG, "Looking for pkg : " + pkgName);
15419
15420                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15421                    if (ps == null) {
15422                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15423                        continue;
15424                    }
15425
15426                    /*
15427                     * Skip packages that are not external if we're unmounting
15428                     * external storage.
15429                     */
15430                    if (externalStorage && !isMounted && !isExternal(ps)) {
15431                        continue;
15432                    }
15433
15434                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15435                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15436                    // The package status is changed only if the code path
15437                    // matches between settings and the container id.
15438                    if (ps.codePathString != null
15439                            && ps.codePathString.startsWith(args.getCodePath())) {
15440                        if (DEBUG_SD_INSTALL) {
15441                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15442                                    + " at code path: " + ps.codePathString);
15443                        }
15444
15445                        // We do have a valid package installed on sdcard
15446                        processCids.put(args, ps.codePathString);
15447                        final int uid = ps.appId;
15448                        if (uid != -1) {
15449                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15450                        }
15451                    } else {
15452                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15453                                + ps.codePathString);
15454                    }
15455                }
15456            }
15457
15458            Arrays.sort(uidArr);
15459        }
15460
15461        // Process packages with valid entries.
15462        if (isMounted) {
15463            if (DEBUG_SD_INSTALL)
15464                Log.i(TAG, "Loading packages");
15465            loadMediaPackages(processCids, uidArr);
15466            startCleaningPackages();
15467            mInstallerService.onSecureContainersAvailable();
15468        } else {
15469            if (DEBUG_SD_INSTALL)
15470                Log.i(TAG, "Unloading packages");
15471            unloadMediaPackages(processCids, uidArr, reportStatus);
15472        }
15473    }
15474
15475    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15476            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15477        final int size = infos.size();
15478        final String[] packageNames = new String[size];
15479        final int[] packageUids = new int[size];
15480        for (int i = 0; i < size; i++) {
15481            final ApplicationInfo info = infos.get(i);
15482            packageNames[i] = info.packageName;
15483            packageUids[i] = info.uid;
15484        }
15485        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15486                finishedReceiver);
15487    }
15488
15489    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15490            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15491        sendResourcesChangedBroadcast(mediaStatus, replacing,
15492                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15493    }
15494
15495    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15496            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15497        int size = pkgList.length;
15498        if (size > 0) {
15499            // Send broadcasts here
15500            Bundle extras = new Bundle();
15501            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15502            if (uidArr != null) {
15503                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15504            }
15505            if (replacing) {
15506                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15507            }
15508            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15509                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15510            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15511        }
15512    }
15513
15514   /*
15515     * Look at potentially valid container ids from processCids If package
15516     * information doesn't match the one on record or package scanning fails,
15517     * the cid is added to list of removeCids. We currently don't delete stale
15518     * containers.
15519     */
15520    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15521        ArrayList<String> pkgList = new ArrayList<String>();
15522        Set<AsecInstallArgs> keys = processCids.keySet();
15523
15524        for (AsecInstallArgs args : keys) {
15525            String codePath = processCids.get(args);
15526            if (DEBUG_SD_INSTALL)
15527                Log.i(TAG, "Loading container : " + args.cid);
15528            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15529            try {
15530                // Make sure there are no container errors first.
15531                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15532                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15533                            + " when installing from sdcard");
15534                    continue;
15535                }
15536                // Check code path here.
15537                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15538                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15539                            + " does not match one in settings " + codePath);
15540                    continue;
15541                }
15542                // Parse package
15543                int parseFlags = mDefParseFlags;
15544                if (args.isExternalAsec()) {
15545                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15546                }
15547                if (args.isFwdLocked()) {
15548                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15549                }
15550
15551                synchronized (mInstallLock) {
15552                    PackageParser.Package pkg = null;
15553                    try {
15554                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15555                    } catch (PackageManagerException e) {
15556                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15557                    }
15558                    // Scan the package
15559                    if (pkg != null) {
15560                        /*
15561                         * TODO why is the lock being held? doPostInstall is
15562                         * called in other places without the lock. This needs
15563                         * to be straightened out.
15564                         */
15565                        // writer
15566                        synchronized (mPackages) {
15567                            retCode = PackageManager.INSTALL_SUCCEEDED;
15568                            pkgList.add(pkg.packageName);
15569                            // Post process args
15570                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15571                                    pkg.applicationInfo.uid);
15572                        }
15573                    } else {
15574                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15575                    }
15576                }
15577
15578            } finally {
15579                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15580                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15581                }
15582            }
15583        }
15584        // writer
15585        synchronized (mPackages) {
15586            // If the platform SDK has changed since the last time we booted,
15587            // we need to re-grant app permission to catch any new ones that
15588            // appear. This is really a hack, and means that apps can in some
15589            // cases get permissions that the user didn't initially explicitly
15590            // allow... it would be nice to have some better way to handle
15591            // this situation.
15592            final VersionInfo ver = mSettings.getExternalVersion();
15593
15594            int updateFlags = UPDATE_PERMISSIONS_ALL;
15595            if (ver.sdkVersion != mSdkVersion) {
15596                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15597                        + mSdkVersion + "; regranting permissions for external");
15598                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15599            }
15600            updatePermissionsLPw(null, null, updateFlags);
15601
15602            // Yay, everything is now upgraded
15603            ver.forceCurrent();
15604
15605            // can downgrade to reader
15606            // Persist settings
15607            mSettings.writeLPr();
15608        }
15609        // Send a broadcast to let everyone know we are done processing
15610        if (pkgList.size() > 0) {
15611            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15612        }
15613    }
15614
15615   /*
15616     * Utility method to unload a list of specified containers
15617     */
15618    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15619        // Just unmount all valid containers.
15620        for (AsecInstallArgs arg : cidArgs) {
15621            synchronized (mInstallLock) {
15622                arg.doPostDeleteLI(false);
15623           }
15624       }
15625   }
15626
15627    /*
15628     * Unload packages mounted on external media. This involves deleting package
15629     * data from internal structures, sending broadcasts about diabled packages,
15630     * gc'ing to free up references, unmounting all secure containers
15631     * corresponding to packages on external media, and posting a
15632     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15633     * that we always have to post this message if status has been requested no
15634     * matter what.
15635     */
15636    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15637            final boolean reportStatus) {
15638        if (DEBUG_SD_INSTALL)
15639            Log.i(TAG, "unloading media packages");
15640        ArrayList<String> pkgList = new ArrayList<String>();
15641        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15642        final Set<AsecInstallArgs> keys = processCids.keySet();
15643        for (AsecInstallArgs args : keys) {
15644            String pkgName = args.getPackageName();
15645            if (DEBUG_SD_INSTALL)
15646                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15647            // Delete package internally
15648            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15649            synchronized (mInstallLock) {
15650                boolean res = deletePackageLI(pkgName, null, false, null, null,
15651                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15652                if (res) {
15653                    pkgList.add(pkgName);
15654                } else {
15655                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15656                    failedList.add(args);
15657                }
15658            }
15659        }
15660
15661        // reader
15662        synchronized (mPackages) {
15663            // We didn't update the settings after removing each package;
15664            // write them now for all packages.
15665            mSettings.writeLPr();
15666        }
15667
15668        // We have to absolutely send UPDATED_MEDIA_STATUS only
15669        // after confirming that all the receivers processed the ordered
15670        // broadcast when packages get disabled, force a gc to clean things up.
15671        // and unload all the containers.
15672        if (pkgList.size() > 0) {
15673            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15674                    new IIntentReceiver.Stub() {
15675                public void performReceive(Intent intent, int resultCode, String data,
15676                        Bundle extras, boolean ordered, boolean sticky,
15677                        int sendingUser) throws RemoteException {
15678                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15679                            reportStatus ? 1 : 0, 1, keys);
15680                    mHandler.sendMessage(msg);
15681                }
15682            });
15683        } else {
15684            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15685                    keys);
15686            mHandler.sendMessage(msg);
15687        }
15688    }
15689
15690    private void loadPrivatePackages(final VolumeInfo vol) {
15691        mHandler.post(new Runnable() {
15692            @Override
15693            public void run() {
15694                loadPrivatePackagesInner(vol);
15695            }
15696        });
15697    }
15698
15699    private void loadPrivatePackagesInner(VolumeInfo vol) {
15700        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15701        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15702
15703        final VersionInfo ver;
15704        final List<PackageSetting> packages;
15705        synchronized (mPackages) {
15706            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15707            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15708        }
15709
15710        for (PackageSetting ps : packages) {
15711            synchronized (mInstallLock) {
15712                final PackageParser.Package pkg;
15713                try {
15714                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15715                    loaded.add(pkg.applicationInfo);
15716                } catch (PackageManagerException e) {
15717                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15718                }
15719
15720                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15721                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15722                }
15723            }
15724        }
15725
15726        synchronized (mPackages) {
15727            int updateFlags = UPDATE_PERMISSIONS_ALL;
15728            if (ver.sdkVersion != mSdkVersion) {
15729                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15730                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15731                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15732            }
15733            updatePermissionsLPw(null, null, updateFlags);
15734
15735            // Yay, everything is now upgraded
15736            ver.forceCurrent();
15737
15738            mSettings.writeLPr();
15739        }
15740
15741        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15742        sendResourcesChangedBroadcast(true, false, loaded, null);
15743    }
15744
15745    private void unloadPrivatePackages(final VolumeInfo vol) {
15746        mHandler.post(new Runnable() {
15747            @Override
15748            public void run() {
15749                unloadPrivatePackagesInner(vol);
15750            }
15751        });
15752    }
15753
15754    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15755        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15756        synchronized (mInstallLock) {
15757        synchronized (mPackages) {
15758            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15759            for (PackageSetting ps : packages) {
15760                if (ps.pkg == null) continue;
15761
15762                final ApplicationInfo info = ps.pkg.applicationInfo;
15763                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15764                if (deletePackageLI(ps.name, null, false, null, null,
15765                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15766                    unloaded.add(info);
15767                } else {
15768                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15769                }
15770            }
15771
15772            mSettings.writeLPr();
15773        }
15774        }
15775
15776        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15777        sendResourcesChangedBroadcast(false, false, unloaded, null);
15778    }
15779
15780    /**
15781     * Examine all users present on given mounted volume, and destroy data
15782     * belonging to users that are no longer valid, or whose user ID has been
15783     * recycled.
15784     */
15785    private void reconcileUsers(String volumeUuid) {
15786        final File[] files = FileUtils
15787                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15788        for (File file : files) {
15789            if (!file.isDirectory()) continue;
15790
15791            final int userId;
15792            final UserInfo info;
15793            try {
15794                userId = Integer.parseInt(file.getName());
15795                info = sUserManager.getUserInfo(userId);
15796            } catch (NumberFormatException e) {
15797                Slog.w(TAG, "Invalid user directory " + file);
15798                continue;
15799            }
15800
15801            boolean destroyUser = false;
15802            if (info == null) {
15803                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15804                        + " because no matching user was found");
15805                destroyUser = true;
15806            } else {
15807                try {
15808                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15809                } catch (IOException e) {
15810                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15811                            + " because we failed to enforce serial number: " + e);
15812                    destroyUser = true;
15813                }
15814            }
15815
15816            if (destroyUser) {
15817                synchronized (mInstallLock) {
15818                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15819                }
15820            }
15821        }
15822
15823        final UserManager um = mContext.getSystemService(UserManager.class);
15824        for (UserInfo user : um.getUsers()) {
15825            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15826            if (userDir.exists()) continue;
15827
15828            try {
15829                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15830                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15831            } catch (IOException e) {
15832                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15833            }
15834        }
15835    }
15836
15837    /**
15838     * Examine all apps present on given mounted volume, and destroy apps that
15839     * aren't expected, either due to uninstallation or reinstallation on
15840     * another volume.
15841     */
15842    private void reconcileApps(String volumeUuid) {
15843        final File[] files = FileUtils
15844                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15845        for (File file : files) {
15846            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15847                    && !PackageInstallerService.isStageName(file.getName());
15848            if (!isPackage) {
15849                // Ignore entries which are not packages
15850                continue;
15851            }
15852
15853            boolean destroyApp = false;
15854            String packageName = null;
15855            try {
15856                final PackageLite pkg = PackageParser.parsePackageLite(file,
15857                        PackageParser.PARSE_MUST_BE_APK);
15858                packageName = pkg.packageName;
15859
15860                synchronized (mPackages) {
15861                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15862                    if (ps == null) {
15863                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15864                                + volumeUuid + " because we found no install record");
15865                        destroyApp = true;
15866                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15867                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15868                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15869                        destroyApp = true;
15870                    }
15871                }
15872
15873            } catch (PackageParserException e) {
15874                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15875                destroyApp = true;
15876            }
15877
15878            if (destroyApp) {
15879                synchronized (mInstallLock) {
15880                    if (packageName != null) {
15881                        removeDataDirsLI(volumeUuid, packageName);
15882                    }
15883                    if (file.isDirectory()) {
15884                        mInstaller.rmPackageDir(file.getAbsolutePath());
15885                    } else {
15886                        file.delete();
15887                    }
15888                }
15889            }
15890        }
15891    }
15892
15893    private void unfreezePackage(String packageName) {
15894        synchronized (mPackages) {
15895            final PackageSetting ps = mSettings.mPackages.get(packageName);
15896            if (ps != null) {
15897                ps.frozen = false;
15898            }
15899        }
15900    }
15901
15902    @Override
15903    public int movePackage(final String packageName, final String volumeUuid) {
15904        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15905
15906        final int moveId = mNextMoveId.getAndIncrement();
15907        try {
15908            movePackageInternal(packageName, volumeUuid, moveId);
15909        } catch (PackageManagerException e) {
15910            Slog.w(TAG, "Failed to move " + packageName, e);
15911            mMoveCallbacks.notifyStatusChanged(moveId,
15912                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15913        }
15914        return moveId;
15915    }
15916
15917    private void movePackageInternal(final String packageName, final String volumeUuid,
15918            final int moveId) throws PackageManagerException {
15919        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15920        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15921        final PackageManager pm = mContext.getPackageManager();
15922
15923        final boolean currentAsec;
15924        final String currentVolumeUuid;
15925        final File codeFile;
15926        final String installerPackageName;
15927        final String packageAbiOverride;
15928        final int appId;
15929        final String seinfo;
15930        final String label;
15931
15932        // reader
15933        synchronized (mPackages) {
15934            final PackageParser.Package pkg = mPackages.get(packageName);
15935            final PackageSetting ps = mSettings.mPackages.get(packageName);
15936            if (pkg == null || ps == null) {
15937                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15938            }
15939
15940            if (pkg.applicationInfo.isSystemApp()) {
15941                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15942                        "Cannot move system application");
15943            }
15944
15945            if (pkg.applicationInfo.isExternalAsec()) {
15946                currentAsec = true;
15947                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15948            } else if (pkg.applicationInfo.isForwardLocked()) {
15949                currentAsec = true;
15950                currentVolumeUuid = "forward_locked";
15951            } else {
15952                currentAsec = false;
15953                currentVolumeUuid = ps.volumeUuid;
15954
15955                final File probe = new File(pkg.codePath);
15956                final File probeOat = new File(probe, "oat");
15957                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15958                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15959                            "Move only supported for modern cluster style installs");
15960                }
15961            }
15962
15963            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15964                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15965                        "Package already moved to " + volumeUuid);
15966            }
15967
15968            if (ps.frozen) {
15969                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15970                        "Failed to move already frozen package");
15971            }
15972            ps.frozen = true;
15973
15974            codeFile = new File(pkg.codePath);
15975            installerPackageName = ps.installerPackageName;
15976            packageAbiOverride = ps.cpuAbiOverrideString;
15977            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15978            seinfo = pkg.applicationInfo.seinfo;
15979            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15980        }
15981
15982        // Now that we're guarded by frozen state, kill app during move
15983        final long token = Binder.clearCallingIdentity();
15984        try {
15985            killApplication(packageName, appId, "move pkg");
15986        } finally {
15987            Binder.restoreCallingIdentity(token);
15988        }
15989
15990        final Bundle extras = new Bundle();
15991        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15992        extras.putString(Intent.EXTRA_TITLE, label);
15993        mMoveCallbacks.notifyCreated(moveId, extras);
15994
15995        int installFlags;
15996        final boolean moveCompleteApp;
15997        final File measurePath;
15998
15999        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16000            installFlags = INSTALL_INTERNAL;
16001            moveCompleteApp = !currentAsec;
16002            measurePath = Environment.getDataAppDirectory(volumeUuid);
16003        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16004            installFlags = INSTALL_EXTERNAL;
16005            moveCompleteApp = false;
16006            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16007        } else {
16008            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16009            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16010                    || !volume.isMountedWritable()) {
16011                unfreezePackage(packageName);
16012                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16013                        "Move location not mounted private volume");
16014            }
16015
16016            Preconditions.checkState(!currentAsec);
16017
16018            installFlags = INSTALL_INTERNAL;
16019            moveCompleteApp = true;
16020            measurePath = Environment.getDataAppDirectory(volumeUuid);
16021        }
16022
16023        final PackageStats stats = new PackageStats(null, -1);
16024        synchronized (mInstaller) {
16025            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16026                unfreezePackage(packageName);
16027                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16028                        "Failed to measure package size");
16029            }
16030        }
16031
16032        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16033                + stats.dataSize);
16034
16035        final long startFreeBytes = measurePath.getFreeSpace();
16036        final long sizeBytes;
16037        if (moveCompleteApp) {
16038            sizeBytes = stats.codeSize + stats.dataSize;
16039        } else {
16040            sizeBytes = stats.codeSize;
16041        }
16042
16043        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16044            unfreezePackage(packageName);
16045            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16046                    "Not enough free space to move");
16047        }
16048
16049        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16050
16051        final CountDownLatch installedLatch = new CountDownLatch(1);
16052        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16053            @Override
16054            public void onUserActionRequired(Intent intent) throws RemoteException {
16055                throw new IllegalStateException();
16056            }
16057
16058            @Override
16059            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16060                    Bundle extras) throws RemoteException {
16061                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16062                        + PackageManager.installStatusToString(returnCode, msg));
16063
16064                installedLatch.countDown();
16065
16066                // Regardless of success or failure of the move operation,
16067                // always unfreeze the package
16068                unfreezePackage(packageName);
16069
16070                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16071                switch (status) {
16072                    case PackageInstaller.STATUS_SUCCESS:
16073                        mMoveCallbacks.notifyStatusChanged(moveId,
16074                                PackageManager.MOVE_SUCCEEDED);
16075                        break;
16076                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16077                        mMoveCallbacks.notifyStatusChanged(moveId,
16078                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16079                        break;
16080                    default:
16081                        mMoveCallbacks.notifyStatusChanged(moveId,
16082                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16083                        break;
16084                }
16085            }
16086        };
16087
16088        final MoveInfo move;
16089        if (moveCompleteApp) {
16090            // Kick off a thread to report progress estimates
16091            new Thread() {
16092                @Override
16093                public void run() {
16094                    while (true) {
16095                        try {
16096                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16097                                break;
16098                            }
16099                        } catch (InterruptedException ignored) {
16100                        }
16101
16102                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16103                        final int progress = 10 + (int) MathUtils.constrain(
16104                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16105                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16106                    }
16107                }
16108            }.start();
16109
16110            final String dataAppName = codeFile.getName();
16111            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16112                    dataAppName, appId, seinfo);
16113        } else {
16114            move = null;
16115        }
16116
16117        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16118
16119        final Message msg = mHandler.obtainMessage(INIT_COPY);
16120        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16121        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16122                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16123        mHandler.sendMessage(msg);
16124    }
16125
16126    @Override
16127    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16129
16130        final int realMoveId = mNextMoveId.getAndIncrement();
16131        final Bundle extras = new Bundle();
16132        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16133        mMoveCallbacks.notifyCreated(realMoveId, extras);
16134
16135        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16136            @Override
16137            public void onCreated(int moveId, Bundle extras) {
16138                // Ignored
16139            }
16140
16141            @Override
16142            public void onStatusChanged(int moveId, int status, long estMillis) {
16143                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16144            }
16145        };
16146
16147        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16148        storage.setPrimaryStorageUuid(volumeUuid, callback);
16149        return realMoveId;
16150    }
16151
16152    @Override
16153    public int getMoveStatus(int moveId) {
16154        mContext.enforceCallingOrSelfPermission(
16155                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16156        return mMoveCallbacks.mLastStatus.get(moveId);
16157    }
16158
16159    @Override
16160    public void registerMoveCallback(IPackageMoveObserver callback) {
16161        mContext.enforceCallingOrSelfPermission(
16162                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16163        mMoveCallbacks.register(callback);
16164    }
16165
16166    @Override
16167    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16168        mContext.enforceCallingOrSelfPermission(
16169                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16170        mMoveCallbacks.unregister(callback);
16171    }
16172
16173    @Override
16174    public boolean setInstallLocation(int loc) {
16175        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16176                null);
16177        if (getInstallLocation() == loc) {
16178            return true;
16179        }
16180        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16181                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16182            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16183                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16184            return true;
16185        }
16186        return false;
16187   }
16188
16189    @Override
16190    public int getInstallLocation() {
16191        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16192                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16193                PackageHelper.APP_INSTALL_AUTO);
16194    }
16195
16196    /** Called by UserManagerService */
16197    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16198        mDirtyUsers.remove(userHandle);
16199        mSettings.removeUserLPw(userHandle);
16200        mPendingBroadcasts.remove(userHandle);
16201        if (mInstaller != null) {
16202            // Technically, we shouldn't be doing this with the package lock
16203            // held.  However, this is very rare, and there is already so much
16204            // other disk I/O going on, that we'll let it slide for now.
16205            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16206            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16207                final String volumeUuid = vol.getFsUuid();
16208                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16209                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16210            }
16211        }
16212        mUserNeedsBadging.delete(userHandle);
16213        removeUnusedPackagesLILPw(userManager, userHandle);
16214    }
16215
16216    /**
16217     * We're removing userHandle and would like to remove any downloaded packages
16218     * that are no longer in use by any other user.
16219     * @param userHandle the user being removed
16220     */
16221    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16222        final boolean DEBUG_CLEAN_APKS = false;
16223        int [] users = userManager.getUserIdsLPr();
16224        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16225        while (psit.hasNext()) {
16226            PackageSetting ps = psit.next();
16227            if (ps.pkg == null) {
16228                continue;
16229            }
16230            final String packageName = ps.pkg.packageName;
16231            // Skip over if system app
16232            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16233                continue;
16234            }
16235            if (DEBUG_CLEAN_APKS) {
16236                Slog.i(TAG, "Checking package " + packageName);
16237            }
16238            boolean keep = false;
16239            for (int i = 0; i < users.length; i++) {
16240                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16241                    keep = true;
16242                    if (DEBUG_CLEAN_APKS) {
16243                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16244                                + users[i]);
16245                    }
16246                    break;
16247                }
16248            }
16249            if (!keep) {
16250                if (DEBUG_CLEAN_APKS) {
16251                    Slog.i(TAG, "  Removing package " + packageName);
16252                }
16253                mHandler.post(new Runnable() {
16254                    public void run() {
16255                        deletePackageX(packageName, userHandle, 0);
16256                    } //end run
16257                });
16258            }
16259        }
16260    }
16261
16262    /** Called by UserManagerService */
16263    void createNewUserLILPw(int userHandle) {
16264        if (mInstaller != null) {
16265            mInstaller.createUserConfig(userHandle);
16266            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16267            applyFactoryDefaultBrowserLPw(userHandle);
16268            primeDomainVerificationsLPw(userHandle);
16269        }
16270    }
16271
16272    void newUserCreated(final int userHandle) {
16273        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16274    }
16275
16276    @Override
16277    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16278        mContext.enforceCallingOrSelfPermission(
16279                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16280                "Only package verification agents can read the verifier device identity");
16281
16282        synchronized (mPackages) {
16283            return mSettings.getVerifierDeviceIdentityLPw();
16284        }
16285    }
16286
16287    @Override
16288    public void setPermissionEnforced(String permission, boolean enforced) {
16289        // TODO: Now that we no longer change GID for storage, this should to away.
16290        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16291                "setPermissionEnforced");
16292        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16293            synchronized (mPackages) {
16294                if (mSettings.mReadExternalStorageEnforced == null
16295                        || mSettings.mReadExternalStorageEnforced != enforced) {
16296                    mSettings.mReadExternalStorageEnforced = enforced;
16297                    mSettings.writeLPr();
16298                }
16299            }
16300            // kill any non-foreground processes so we restart them and
16301            // grant/revoke the GID.
16302            final IActivityManager am = ActivityManagerNative.getDefault();
16303            if (am != null) {
16304                final long token = Binder.clearCallingIdentity();
16305                try {
16306                    am.killProcessesBelowForeground("setPermissionEnforcement");
16307                } catch (RemoteException e) {
16308                } finally {
16309                    Binder.restoreCallingIdentity(token);
16310                }
16311            }
16312        } else {
16313            throw new IllegalArgumentException("No selective enforcement for " + permission);
16314        }
16315    }
16316
16317    @Override
16318    @Deprecated
16319    public boolean isPermissionEnforced(String permission) {
16320        return true;
16321    }
16322
16323    @Override
16324    public boolean isStorageLow() {
16325        final long token = Binder.clearCallingIdentity();
16326        try {
16327            final DeviceStorageMonitorInternal
16328                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16329            if (dsm != null) {
16330                return dsm.isMemoryLow();
16331            } else {
16332                return false;
16333            }
16334        } finally {
16335            Binder.restoreCallingIdentity(token);
16336        }
16337    }
16338
16339    @Override
16340    public IPackageInstaller getPackageInstaller() {
16341        return mInstallerService;
16342    }
16343
16344    private boolean userNeedsBadging(int userId) {
16345        int index = mUserNeedsBadging.indexOfKey(userId);
16346        if (index < 0) {
16347            final UserInfo userInfo;
16348            final long token = Binder.clearCallingIdentity();
16349            try {
16350                userInfo = sUserManager.getUserInfo(userId);
16351            } finally {
16352                Binder.restoreCallingIdentity(token);
16353            }
16354            final boolean b;
16355            if (userInfo != null && userInfo.isManagedProfile()) {
16356                b = true;
16357            } else {
16358                b = false;
16359            }
16360            mUserNeedsBadging.put(userId, b);
16361            return b;
16362        }
16363        return mUserNeedsBadging.valueAt(index);
16364    }
16365
16366    @Override
16367    public KeySet getKeySetByAlias(String packageName, String alias) {
16368        if (packageName == null || alias == null) {
16369            return null;
16370        }
16371        synchronized(mPackages) {
16372            final PackageParser.Package pkg = mPackages.get(packageName);
16373            if (pkg == null) {
16374                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16375                throw new IllegalArgumentException("Unknown package: " + packageName);
16376            }
16377            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16378            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16379        }
16380    }
16381
16382    @Override
16383    public KeySet getSigningKeySet(String packageName) {
16384        if (packageName == null) {
16385            return null;
16386        }
16387        synchronized(mPackages) {
16388            final PackageParser.Package pkg = mPackages.get(packageName);
16389            if (pkg == null) {
16390                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16391                throw new IllegalArgumentException("Unknown package: " + packageName);
16392            }
16393            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16394                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16395                throw new SecurityException("May not access signing KeySet of other apps.");
16396            }
16397            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16398            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16399        }
16400    }
16401
16402    @Override
16403    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16404        if (packageName == null || ks == null) {
16405            return false;
16406        }
16407        synchronized(mPackages) {
16408            final PackageParser.Package pkg = mPackages.get(packageName);
16409            if (pkg == null) {
16410                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16411                throw new IllegalArgumentException("Unknown package: " + packageName);
16412            }
16413            IBinder ksh = ks.getToken();
16414            if (ksh instanceof KeySetHandle) {
16415                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16416                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16417            }
16418            return false;
16419        }
16420    }
16421
16422    @Override
16423    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16424        if (packageName == null || ks == null) {
16425            return false;
16426        }
16427        synchronized(mPackages) {
16428            final PackageParser.Package pkg = mPackages.get(packageName);
16429            if (pkg == null) {
16430                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16431                throw new IllegalArgumentException("Unknown package: " + packageName);
16432            }
16433            IBinder ksh = ks.getToken();
16434            if (ksh instanceof KeySetHandle) {
16435                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16436                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16437            }
16438            return false;
16439        }
16440    }
16441
16442    public void getUsageStatsIfNoPackageUsageInfo() {
16443        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16444            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16445            if (usm == null) {
16446                throw new IllegalStateException("UsageStatsManager must be initialized");
16447            }
16448            long now = System.currentTimeMillis();
16449            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16450            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16451                String packageName = entry.getKey();
16452                PackageParser.Package pkg = mPackages.get(packageName);
16453                if (pkg == null) {
16454                    continue;
16455                }
16456                UsageStats usage = entry.getValue();
16457                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16458                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16459            }
16460        }
16461    }
16462
16463    /**
16464     * Check and throw if the given before/after packages would be considered a
16465     * downgrade.
16466     */
16467    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16468            throws PackageManagerException {
16469        if (after.versionCode < before.mVersionCode) {
16470            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16471                    "Update version code " + after.versionCode + " is older than current "
16472                    + before.mVersionCode);
16473        } else if (after.versionCode == before.mVersionCode) {
16474            if (after.baseRevisionCode < before.baseRevisionCode) {
16475                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16476                        "Update base revision code " + after.baseRevisionCode
16477                        + " is older than current " + before.baseRevisionCode);
16478            }
16479
16480            if (!ArrayUtils.isEmpty(after.splitNames)) {
16481                for (int i = 0; i < after.splitNames.length; i++) {
16482                    final String splitName = after.splitNames[i];
16483                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16484                    if (j != -1) {
16485                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16486                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16487                                    "Update split " + splitName + " revision code "
16488                                    + after.splitRevisionCodes[i] + " is older than current "
16489                                    + before.splitRevisionCodes[j]);
16490                        }
16491                    }
16492                }
16493            }
16494        }
16495    }
16496
16497    private static class MoveCallbacks extends Handler {
16498        private static final int MSG_CREATED = 1;
16499        private static final int MSG_STATUS_CHANGED = 2;
16500
16501        private final RemoteCallbackList<IPackageMoveObserver>
16502                mCallbacks = new RemoteCallbackList<>();
16503
16504        private final SparseIntArray mLastStatus = new SparseIntArray();
16505
16506        public MoveCallbacks(Looper looper) {
16507            super(looper);
16508        }
16509
16510        public void register(IPackageMoveObserver callback) {
16511            mCallbacks.register(callback);
16512        }
16513
16514        public void unregister(IPackageMoveObserver callback) {
16515            mCallbacks.unregister(callback);
16516        }
16517
16518        @Override
16519        public void handleMessage(Message msg) {
16520            final SomeArgs args = (SomeArgs) msg.obj;
16521            final int n = mCallbacks.beginBroadcast();
16522            for (int i = 0; i < n; i++) {
16523                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16524                try {
16525                    invokeCallback(callback, msg.what, args);
16526                } catch (RemoteException ignored) {
16527                }
16528            }
16529            mCallbacks.finishBroadcast();
16530            args.recycle();
16531        }
16532
16533        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16534                throws RemoteException {
16535            switch (what) {
16536                case MSG_CREATED: {
16537                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16538                    break;
16539                }
16540                case MSG_STATUS_CHANGED: {
16541                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16542                    break;
16543                }
16544            }
16545        }
16546
16547        private void notifyCreated(int moveId, Bundle extras) {
16548            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16549
16550            final SomeArgs args = SomeArgs.obtain();
16551            args.argi1 = moveId;
16552            args.arg2 = extras;
16553            obtainMessage(MSG_CREATED, args).sendToTarget();
16554        }
16555
16556        private void notifyStatusChanged(int moveId, int status) {
16557            notifyStatusChanged(moveId, status, -1);
16558        }
16559
16560        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16561            Slog.v(TAG, "Move " + moveId + " status " + status);
16562
16563            final SomeArgs args = SomeArgs.obtain();
16564            args.argi1 = moveId;
16565            args.argi2 = status;
16566            args.arg3 = estMillis;
16567            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16568
16569            synchronized (mLastStatus) {
16570                mLastStatus.put(moveId, status);
16571            }
16572        }
16573    }
16574
16575    private final class OnPermissionChangeListeners extends Handler {
16576        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16577
16578        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16579                new RemoteCallbackList<>();
16580
16581        public OnPermissionChangeListeners(Looper looper) {
16582            super(looper);
16583        }
16584
16585        @Override
16586        public void handleMessage(Message msg) {
16587            switch (msg.what) {
16588                case MSG_ON_PERMISSIONS_CHANGED: {
16589                    final int uid = msg.arg1;
16590                    handleOnPermissionsChanged(uid);
16591                } break;
16592            }
16593        }
16594
16595        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16596            mPermissionListeners.register(listener);
16597
16598        }
16599
16600        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16601            mPermissionListeners.unregister(listener);
16602        }
16603
16604        public void onPermissionsChanged(int uid) {
16605            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16606                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16607            }
16608        }
16609
16610        private void handleOnPermissionsChanged(int uid) {
16611            final int count = mPermissionListeners.beginBroadcast();
16612            try {
16613                for (int i = 0; i < count; i++) {
16614                    IOnPermissionsChangeListener callback = mPermissionListeners
16615                            .getBroadcastItem(i);
16616                    try {
16617                        callback.onPermissionsChanged(uid);
16618                    } catch (RemoteException e) {
16619                        Log.e(TAG, "Permission listener is dead", e);
16620                    }
16621                }
16622            } finally {
16623                mPermissionListeners.finishBroadcast();
16624            }
16625        }
16626    }
16627
16628    private class PackageManagerInternalImpl extends PackageManagerInternal {
16629        @Override
16630        public void setLocationPackagesProvider(PackagesProvider provider) {
16631            synchronized (mPackages) {
16632                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16633            }
16634        }
16635
16636        @Override
16637        public void setImePackagesProvider(PackagesProvider provider) {
16638            synchronized (mPackages) {
16639                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16640            }
16641        }
16642
16643        @Override
16644        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16645            synchronized (mPackages) {
16646                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16647            }
16648        }
16649
16650        @Override
16651        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16652            synchronized (mPackages) {
16653                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16654            }
16655        }
16656
16657        @Override
16658        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16659            synchronized (mPackages) {
16660                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16661            }
16662        }
16663
16664        @Override
16665        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16666            synchronized (mPackages) {
16667                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16668            }
16669        }
16670
16671        @Override
16672        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16673            synchronized (mPackages) {
16674                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16675            }
16676        }
16677
16678        @Override
16679        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16680            synchronized (mPackages) {
16681                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16682                        packageName, userId);
16683            }
16684        }
16685
16686        @Override
16687        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16688            synchronized (mPackages) {
16689                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16690                        packageName, userId);
16691            }
16692        }
16693        @Override
16694        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16695            synchronized (mPackages) {
16696                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16697                        packageName, userId);
16698            }
16699        }
16700    }
16701
16702    @Override
16703    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16704        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16705        synchronized (mPackages) {
16706            final long identity = Binder.clearCallingIdentity();
16707            try {
16708                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16709                        packageNames, userId);
16710            } finally {
16711                Binder.restoreCallingIdentity(identity);
16712            }
16713        }
16714    }
16715
16716    private static void enforceSystemOrPhoneCaller(String tag) {
16717        int callingUid = Binder.getCallingUid();
16718        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16719            throw new SecurityException(
16720                    "Cannot call " + tag + " from UID " + callingUid);
16721        }
16722    }
16723}
16724