PackageManagerService.java revision e2ed23e6b221185ce2587fb19a6e904dbf7ec77b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86import android.Manifest;
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IOnPermissionsChangeListener;
108import android.content.pm.IPackageDataObserver;
109import android.content.pm.IPackageDeleteObserver;
110import android.content.pm.IPackageDeleteObserver2;
111import android.content.pm.IPackageInstallObserver2;
112import android.content.pm.IPackageInstaller;
113import android.content.pm.IPackageManager;
114import android.content.pm.IPackageMoveObserver;
115import android.content.pm.IPackageStatsObserver;
116import android.content.pm.InstrumentationInfo;
117import android.content.pm.IntentFilterVerificationInfo;
118import android.content.pm.KeySet;
119import android.content.pm.ManifestDigest;
120import android.content.pm.PackageCleanItem;
121import android.content.pm.PackageInfo;
122import android.content.pm.PackageInfoLite;
123import android.content.pm.PackageInstaller;
124import android.content.pm.PackageManager;
125import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126import android.content.pm.PackageManagerInternal;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageParser.ActivityIntentInfo;
129import android.content.pm.PackageParser.PackageLite;
130import android.content.pm.PackageParser.PackageParserException;
131import android.content.pm.PackageStats;
132import android.content.pm.PackageUserState;
133import android.content.pm.ParceledListSlice;
134import android.content.pm.PermissionGroupInfo;
135import android.content.pm.PermissionInfo;
136import android.content.pm.ProviderInfo;
137import android.content.pm.ResolveInfo;
138import android.content.pm.ServiceInfo;
139import android.content.pm.Signature;
140import android.content.pm.UserInfo;
141import android.content.pm.VerificationParams;
142import android.content.pm.VerifierDeviceIdentity;
143import android.content.pm.VerifierInfo;
144import android.content.res.Resources;
145import android.hardware.display.DisplayManager;
146import android.net.Uri;
147import android.os.Debug;
148import android.os.Binder;
149import android.os.Build;
150import android.os.Bundle;
151import android.os.Environment;
152import android.os.Environment.UserEnvironment;
153import android.os.FileUtils;
154import android.os.Handler;
155import android.os.IBinder;
156import android.os.Looper;
157import android.os.Message;
158import android.os.Parcel;
159import android.os.ParcelFileDescriptor;
160import android.os.Process;
161import android.os.RemoteCallbackList;
162import android.os.RemoteException;
163import android.os.SELinux;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.storage.IMountService;
170import android.os.storage.MountServiceInternal;
171import android.os.storage.StorageEventListener;
172import android.os.storage.StorageManager;
173import android.os.storage.VolumeInfo;
174import android.os.storage.VolumeRecord;
175import android.security.KeyStore;
176import android.security.SystemKeyStore;
177import android.system.ErrnoException;
178import android.system.Os;
179import android.system.StructStat;
180import android.text.TextUtils;
181import android.text.format.DateUtils;
182import android.util.ArrayMap;
183import android.util.ArraySet;
184import android.util.AtomicFile;
185import android.util.DisplayMetrics;
186import android.util.EventLog;
187import android.util.ExceptionUtils;
188import android.util.Log;
189import android.util.LogPrinter;
190import android.util.MathUtils;
191import android.util.PrintStreamPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
196import android.util.Xml;
197import android.view.Display;
198
199import dalvik.system.DexFile;
200import dalvik.system.VMRuntime;
201
202import libcore.io.IoUtils;
203import libcore.util.EmptyArray;
204
205import com.android.internal.R;
206import com.android.internal.annotations.GuardedBy;
207import com.android.internal.app.IMediaContainerService;
208import com.android.internal.app.ResolverActivity;
209import com.android.internal.content.NativeLibraryHelper;
210import com.android.internal.content.PackageHelper;
211import com.android.internal.os.IParcelFileDescriptorFactory;
212import com.android.internal.os.SomeArgs;
213import com.android.internal.os.Zygote;
214import com.android.internal.util.ArrayUtils;
215import com.android.internal.util.FastPrintWriter;
216import com.android.internal.util.FastXmlSerializer;
217import com.android.internal.util.IndentingPrintWriter;
218import com.android.internal.util.Preconditions;
219import com.android.server.EventLogTags;
220import com.android.server.FgThread;
221import com.android.server.IntentResolver;
222import com.android.server.LocalServices;
223import com.android.server.ServiceThread;
224import com.android.server.SystemConfig;
225import com.android.server.Watchdog;
226import com.android.server.pm.PermissionsState.PermissionState;
227import com.android.server.pm.Settings.DatabaseVersion;
228import com.android.server.pm.Settings.VersionInfo;
229import com.android.server.storage.DeviceStorageMonitorInternal;
230
231import org.xmlpull.v1.XmlPullParser;
232import org.xmlpull.v1.XmlPullParserException;
233import org.xmlpull.v1.XmlSerializer;
234
235import java.io.BufferedInputStream;
236import java.io.BufferedOutputStream;
237import java.io.BufferedReader;
238import java.io.ByteArrayInputStream;
239import java.io.ByteArrayOutputStream;
240import java.io.File;
241import java.io.FileDescriptor;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.FileReader;
245import java.io.FilenameFilter;
246import java.io.IOException;
247import java.io.InputStream;
248import java.io.PrintWriter;
249import java.nio.charset.StandardCharsets;
250import java.security.NoSuchAlgorithmException;
251import java.security.PublicKey;
252import java.security.cert.CertificateEncodingException;
253import java.security.cert.CertificateException;
254import java.text.SimpleDateFormat;
255import java.util.ArrayList;
256import java.util.Arrays;
257import java.util.Collection;
258import java.util.Collections;
259import java.util.Comparator;
260import java.util.Date;
261import java.util.Iterator;
262import java.util.List;
263import java.util.Map;
264import java.util.Objects;
265import java.util.Set;
266import java.util.concurrent.CountDownLatch;
267import java.util.concurrent.TimeUnit;
268import java.util.concurrent.atomic.AtomicBoolean;
269import java.util.concurrent.atomic.AtomicInteger;
270import java.util.concurrent.atomic.AtomicLong;
271
272/**
273 * Keep track of all those .apks everywhere.
274 *
275 * This is very central to the platform's security; please run the unit
276 * tests whenever making modifications here:
277 *
278mmm frameworks/base/tests/AndroidTests
279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        // If this is the only one pending we might
1150                        // have to bind to the service again.
1151                        if (!connectToService()) {
1152                            Slog.e(TAG, "Failed to bind to media container service");
1153                            params.serviceError();
1154                            return;
1155                        } else {
1156                            // Once we bind to the service, the first
1157                            // pending request will be processed.
1158                            mPendingInstalls.add(idx, params);
1159                        }
1160                    } else {
1161                        mPendingInstalls.add(idx, params);
1162                        // Already bound to the service. Just make
1163                        // sure we trigger off processing the first request.
1164                        if (idx == 0) {
1165                            mHandler.sendEmptyMessage(MCS_BOUND);
1166                        }
1167                    }
1168                    break;
1169                }
1170                case MCS_BOUND: {
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1172                    if (msg.obj != null) {
1173                        mContainerService = (IMediaContainerService) msg.obj;
1174                    }
1175                    if (mContainerService == null) {
1176                        if (!mBound) {
1177                            // Something seriously wrong since we are not bound and we are not
1178                            // waiting for connection. Bail out.
1179                            Slog.e(TAG, "Cannot bind to media container service");
1180                            for (HandlerParams params : mPendingInstalls) {
1181                                // Indicate service bind error
1182                                params.serviceError();
1183                            }
1184                            mPendingInstalls.clear();
1185                        } else {
1186                            Slog.w(TAG, "Waiting to connect to media container service");
1187                        }
1188                    } else if (mPendingInstalls.size() > 0) {
1189                        HandlerParams params = mPendingInstalls.get(0);
1190                        if (params != null) {
1191                            if (params.startCopy()) {
1192                                // We are done...  look for more work or to
1193                                // go idle.
1194                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1195                                        "Checking for more work or unbind...");
1196                                // Delete pending install
1197                                if (mPendingInstalls.size() > 0) {
1198                                    mPendingInstalls.remove(0);
1199                                }
1200                                if (mPendingInstalls.size() == 0) {
1201                                    if (mBound) {
1202                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                                "Posting delayed MCS_UNBIND");
1204                                        removeMessages(MCS_UNBIND);
1205                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1206                                        // Unbind after a little delay, to avoid
1207                                        // continual thrashing.
1208                                        sendMessageDelayed(ubmsg, 10000);
1209                                    }
1210                                } else {
1211                                    // There are more pending requests in queue.
1212                                    // Just post MCS_BOUND message to trigger processing
1213                                    // of next pending install.
1214                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                            "Posting MCS_BOUND for next work");
1216                                    mHandler.sendEmptyMessage(MCS_BOUND);
1217                                }
1218                            }
1219                        }
1220                    } else {
1221                        // Should never happen ideally.
1222                        Slog.w(TAG, "Empty queue");
1223                    }
1224                    break;
1225                }
1226                case MCS_RECONNECT: {
1227                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1228                    if (mPendingInstalls.size() > 0) {
1229                        if (mBound) {
1230                            disconnectService();
1231                        }
1232                        if (!connectToService()) {
1233                            Slog.e(TAG, "Failed to bind to media container service");
1234                            for (HandlerParams params : mPendingInstalls) {
1235                                // Indicate service bind error
1236                                params.serviceError();
1237                            }
1238                            mPendingInstalls.clear();
1239                        }
1240                    }
1241                    break;
1242                }
1243                case MCS_UNBIND: {
1244                    // If there is no actual work left, then time to unbind.
1245                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1246
1247                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1248                        if (mBound) {
1249                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1250
1251                            disconnectService();
1252                        }
1253                    } else if (mPendingInstalls.size() > 0) {
1254                        // There are more pending requests in queue.
1255                        // Just post MCS_BOUND message to trigger processing
1256                        // of next pending install.
1257                        mHandler.sendEmptyMessage(MCS_BOUND);
1258                    }
1259
1260                    break;
1261                }
1262                case MCS_GIVE_UP: {
1263                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1264                    mPendingInstalls.remove(0);
1265                    break;
1266                }
1267                case SEND_PENDING_BROADCAST: {
1268                    String packages[];
1269                    ArrayList<String> components[];
1270                    int size = 0;
1271                    int uids[];
1272                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1273                    synchronized (mPackages) {
1274                        if (mPendingBroadcasts == null) {
1275                            return;
1276                        }
1277                        size = mPendingBroadcasts.size();
1278                        if (size <= 0) {
1279                            // Nothing to be done. Just return
1280                            return;
1281                        }
1282                        packages = new String[size];
1283                        components = new ArrayList[size];
1284                        uids = new int[size];
1285                        int i = 0;  // filling out the above arrays
1286
1287                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1288                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1289                            Iterator<Map.Entry<String, ArrayList<String>>> it
1290                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1291                                            .entrySet().iterator();
1292                            while (it.hasNext() && i < size) {
1293                                Map.Entry<String, ArrayList<String>> ent = it.next();
1294                                packages[i] = ent.getKey();
1295                                components[i] = ent.getValue();
1296                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1297                                uids[i] = (ps != null)
1298                                        ? UserHandle.getUid(packageUserId, ps.appId)
1299                                        : -1;
1300                                i++;
1301                            }
1302                        }
1303                        size = i;
1304                        mPendingBroadcasts.clear();
1305                    }
1306                    // Send broadcasts
1307                    for (int i = 0; i < size; i++) {
1308                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1309                    }
1310                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1311                    break;
1312                }
1313                case START_CLEANING_PACKAGE: {
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1315                    final String packageName = (String)msg.obj;
1316                    final int userId = msg.arg1;
1317                    final boolean andCode = msg.arg2 != 0;
1318                    synchronized (mPackages) {
1319                        if (userId == UserHandle.USER_ALL) {
1320                            int[] users = sUserManager.getUserIds();
1321                            for (int user : users) {
1322                                mSettings.addPackageToCleanLPw(
1323                                        new PackageCleanItem(user, packageName, andCode));
1324                            }
1325                        } else {
1326                            mSettings.addPackageToCleanLPw(
1327                                    new PackageCleanItem(userId, packageName, andCode));
1328                        }
1329                    }
1330                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1331                    startCleaningPackages();
1332                } break;
1333                case POST_INSTALL: {
1334                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1335                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1336                    mRunningInstalls.delete(msg.arg1);
1337                    boolean deleteOld = false;
1338
1339                    if (data != null) {
1340                        InstallArgs args = data.args;
1341                        PackageInstalledInfo res = data.res;
1342
1343                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1344                            final String packageName = res.pkg.applicationInfo.packageName;
1345                            res.removedInfo.sendBroadcast(false, true, false);
1346                            Bundle extras = new Bundle(1);
1347                            extras.putInt(Intent.EXTRA_UID, res.uid);
1348
1349                            // Now that we successfully installed the package, grant runtime
1350                            // permissions if requested before broadcasting the install.
1351                            if ((args.installFlags
1352                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1353                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1354                                        args.installGrantPermissions);
1355                            }
1356
1357                            // Determine the set of users who are adding this
1358                            // package for the first time vs. those who are seeing
1359                            // an update.
1360                            int[] firstUsers;
1361                            int[] updateUsers = new int[0];
1362                            if (res.origUsers == null || res.origUsers.length == 0) {
1363                                firstUsers = res.newUsers;
1364                            } else {
1365                                firstUsers = new int[0];
1366                                for (int i=0; i<res.newUsers.length; i++) {
1367                                    int user = res.newUsers[i];
1368                                    boolean isNew = true;
1369                                    for (int j=0; j<res.origUsers.length; j++) {
1370                                        if (res.origUsers[j] == user) {
1371                                            isNew = false;
1372                                            break;
1373                                        }
1374                                    }
1375                                    if (isNew) {
1376                                        int[] newFirst = new int[firstUsers.length+1];
1377                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1378                                                firstUsers.length);
1379                                        newFirst[firstUsers.length] = user;
1380                                        firstUsers = newFirst;
1381                                    } else {
1382                                        int[] newUpdate = new int[updateUsers.length+1];
1383                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1384                                                updateUsers.length);
1385                                        newUpdate[updateUsers.length] = user;
1386                                        updateUsers = newUpdate;
1387                                    }
1388                                }
1389                            }
1390                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1391                                    packageName, extras, null, null, firstUsers);
1392                            final boolean update = res.removedInfo.removedPackage != null;
1393                            if (update) {
1394                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1395                            }
1396                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1397                                    packageName, extras, null, null, updateUsers);
1398                            if (update) {
1399                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1400                                        packageName, extras, null, null, updateUsers);
1401                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1402                                        null, null, packageName, null, updateUsers);
1403
1404                                // treat asec-hosted packages like removable media on upgrade
1405                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1406                                    if (DEBUG_INSTALL) {
1407                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1408                                                + " is ASEC-hosted -> AVAILABLE");
1409                                    }
1410                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1411                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1412                                    pkgList.add(packageName);
1413                                    sendResourcesChangedBroadcast(true, true,
1414                                            pkgList,uidArray, null);
1415                                }
1416                            }
1417                            if (res.removedInfo.args != null) {
1418                                // Remove the replaced package's older resources safely now
1419                                deleteOld = true;
1420                            }
1421
1422                            // If this app is a browser and it's newly-installed for some
1423                            // users, clear any default-browser state in those users
1424                            if (firstUsers.length > 0) {
1425                                // the app's nature doesn't depend on the user, so we can just
1426                                // check its browser nature in any user and generalize.
1427                                if (packageIsBrowser(packageName, firstUsers[0])) {
1428                                    synchronized (mPackages) {
1429                                        for (int userId : firstUsers) {
1430                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1431                                        }
1432                                    }
1433                                }
1434                            }
1435                            // Log current value of "unknown sources" setting
1436                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1437                                getUnknownSourcesSettings());
1438                        }
1439                        // Force a gc to clear up things
1440                        Runtime.getRuntime().gc();
1441                        // We delete after a gc for applications  on sdcard.
1442                        if (deleteOld) {
1443                            synchronized (mInstallLock) {
1444                                res.removedInfo.args.doPostDeleteLI(true);
1445                            }
1446                        }
1447                        if (args.observer != null) {
1448                            try {
1449                                Bundle extras = extrasForInstallResult(res);
1450                                args.observer.onPackageInstalled(res.name, res.returnCode,
1451                                        res.returnMsg, extras);
1452                            } catch (RemoteException e) {
1453                                Slog.i(TAG, "Observer no longer exists.");
1454                            }
1455                        }
1456                    } else {
1457                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1458                    }
1459                } break;
1460                case UPDATED_MEDIA_STATUS: {
1461                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1462                    boolean reportStatus = msg.arg1 == 1;
1463                    boolean doGc = msg.arg2 == 1;
1464                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1465                    if (doGc) {
1466                        // Force a gc to clear up stale containers.
1467                        Runtime.getRuntime().gc();
1468                    }
1469                    if (msg.obj != null) {
1470                        @SuppressWarnings("unchecked")
1471                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1472                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1473                        // Unload containers
1474                        unloadAllContainers(args);
1475                    }
1476                    if (reportStatus) {
1477                        try {
1478                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1479                            PackageHelper.getMountService().finishMediaUpdate();
1480                        } catch (RemoteException e) {
1481                            Log.e(TAG, "MountService not running?");
1482                        }
1483                    }
1484                } break;
1485                case WRITE_SETTINGS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_SETTINGS);
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        mSettings.writeLPr();
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case WRITE_PACKAGE_RESTRICTIONS: {
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1497                    synchronized (mPackages) {
1498                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1499                        for (int userId : mDirtyUsers) {
1500                            mSettings.writePackageRestrictionsLPr(userId);
1501                        }
1502                        mDirtyUsers.clear();
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                } break;
1506                case CHECK_PENDING_VERIFICATION: {
1507                    final int verificationId = msg.arg1;
1508                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1509
1510                    if ((state != null) && !state.timeoutExtended()) {
1511                        final InstallArgs args = state.getInstallArgs();
1512                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1513
1514                        Slog.i(TAG, "Verification timed out for " + originUri);
1515                        mPendingVerification.remove(verificationId);
1516
1517                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518
1519                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1520                            Slog.i(TAG, "Continuing with installation of " + originUri);
1521                            state.setVerifierResponse(Binder.getCallingUid(),
1522                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_ALLOW,
1525                                    state.getInstallArgs().getUser());
1526                            try {
1527                                ret = args.copyApk(mContainerService, true);
1528                            } catch (RemoteException e) {
1529                                Slog.e(TAG, "Could not contact the ContainerService");
1530                            }
1531                        } else {
1532                            broadcastPackageVerified(verificationId, originUri,
1533                                    PackageManager.VERIFICATION_REJECT,
1534                                    state.getInstallArgs().getUser());
1535                        }
1536
1537                        processPendingInstall(args, ret);
1538                        mHandler.sendEmptyMessage(MCS_UNBIND);
1539                    }
1540                    break;
1541                }
1542                case PACKAGE_VERIFIED: {
1543                    final int verificationId = msg.arg1;
1544
1545                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1546                    if (state == null) {
1547                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1548                        break;
1549                    }
1550
1551                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1552
1553                    state.setVerifierResponse(response.callerUid, response.code);
1554
1555                    if (state.isVerificationComplete()) {
1556                        mPendingVerification.remove(verificationId);
1557
1558                        final InstallArgs args = state.getInstallArgs();
1559                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1560
1561                        int ret;
1562                        if (state.isInstallAllowed()) {
1563                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    response.code, state.getInstallArgs().getUser());
1566                            try {
1567                                ret = args.copyApk(mContainerService, true);
1568                            } catch (RemoteException e) {
1569                                Slog.e(TAG, "Could not contact the ContainerService");
1570                            }
1571                        } else {
1572                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1573                        }
1574
1575                        processPendingInstall(args, ret);
1576
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579
1580                    break;
1581                }
1582                case START_INTENT_FILTER_VERIFICATIONS: {
1583                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1584                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1585                            params.replacing, params.pkg);
1586                    break;
1587                }
1588                case INTENT_FILTER_VERIFIED: {
1589                    final int verificationId = msg.arg1;
1590
1591                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1592                            verificationId);
1593                    if (state == null) {
1594                        Slog.w(TAG, "Invalid IntentFilter verification token "
1595                                + verificationId + " received");
1596                        break;
1597                    }
1598
1599                    final int userId = state.getUserId();
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "Processing IntentFilter verification with token:"
1603                            + verificationId + " and userId:" + userId);
1604
1605                    final IntentFilterVerificationResponse response =
1606                            (IntentFilterVerificationResponse) msg.obj;
1607
1608                    state.setVerifierResponse(response.callerUid, response.code);
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "IntentFilter verification with token:" + verificationId
1612                            + " and userId:" + userId
1613                            + " is settings verifier response with response code:"
1614                            + response.code);
1615
1616                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1618                                + response.getFailedDomainsString());
1619                    }
1620
1621                    if (state.isVerificationComplete()) {
1622                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1623                    } else {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                                "IntentFilter verification with token:" + verificationId
1626                                + " was not said to be complete");
1627                    }
1628
1629                    break;
1630                }
1631            }
1632        }
1633    }
1634
1635    private StorageEventListener mStorageListener = new StorageEventListener() {
1636        @Override
1637        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1638            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1639                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1640                    final String volumeUuid = vol.getFsUuid();
1641
1642                    // Clean up any users or apps that were removed or recreated
1643                    // while this volume was missing
1644                    reconcileUsers(volumeUuid);
1645                    reconcileApps(volumeUuid);
1646
1647                    // Clean up any install sessions that expired or were
1648                    // cancelled while this volume was missing
1649                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1650
1651                    loadPrivatePackages(vol);
1652
1653                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1654                    unloadPrivatePackages(vol);
1655                }
1656            }
1657
1658            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1659                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1660                    updateExternalMediaStatus(true, false);
1661                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1662                    updateExternalMediaStatus(false, false);
1663                }
1664            }
1665        }
1666
1667        @Override
1668        public void onVolumeForgotten(String fsUuid) {
1669            if (TextUtils.isEmpty(fsUuid)) {
1670                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1671                return;
1672            }
1673
1674            // Remove any apps installed on the forgotten volume
1675            synchronized (mPackages) {
1676                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1677                for (PackageSetting ps : packages) {
1678                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1679                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1680                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1681                }
1682
1683                mSettings.onVolumeForgotten(fsUuid);
1684                mSettings.writeLPr();
1685            }
1686        }
1687    };
1688
1689    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1690            String[] grantedPermissions) {
1691        if (userId >= UserHandle.USER_OWNER) {
1692            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1693        } else if (userId == UserHandle.USER_ALL) {
1694            final int[] userIds;
1695            synchronized (mPackages) {
1696                userIds = UserManagerService.getInstance().getUserIds();
1697            }
1698            for (int someUserId : userIds) {
1699                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1700            }
1701        }
1702
1703        // We could have touched GID membership, so flush out packages.list
1704        synchronized (mPackages) {
1705            mSettings.writePackageListLPr();
1706        }
1707    }
1708
1709    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1710            String[] grantedPermissions) {
1711        SettingBase sb = (SettingBase) pkg.mExtras;
1712        if (sb == null) {
1713            return;
1714        }
1715
1716        synchronized (mPackages) {
1717            for (String permission : pkg.requestedPermissions) {
1718                BasePermission bp = mSettings.mPermissions.get(permission);
1719                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1720                        && (grantedPermissions == null
1721                               || ArrayUtils.contains(grantedPermissions, permission))) {
1722                    grantRuntimePermission(pkg.packageName, permission, userId);
1723                }
1724            }
1725        }
1726    }
1727
1728    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729        Bundle extras = null;
1730        switch (res.returnCode) {
1731            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732                extras = new Bundle();
1733                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734                        res.origPermission);
1735                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1736                        res.origPackage);
1737                break;
1738            }
1739            case PackageManager.INSTALL_SUCCEEDED: {
1740                extras = new Bundle();
1741                extras.putBoolean(Intent.EXTRA_REPLACING,
1742                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1743                break;
1744            }
1745        }
1746        return extras;
1747    }
1748
1749    void scheduleWriteSettingsLocked() {
1750        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1752        }
1753    }
1754
1755    void scheduleWritePackageRestrictionsLocked(int userId) {
1756        if (!sUserManager.exists(userId)) return;
1757        mDirtyUsers.add(userId);
1758        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1760        }
1761    }
1762
1763    public static PackageManagerService main(Context context, Installer installer,
1764            boolean factoryTest, boolean onlyCore) {
1765        PackageManagerService m = new PackageManagerService(context, installer,
1766                factoryTest, onlyCore);
1767        ServiceManager.addService("package", m);
1768        return m;
1769    }
1770
1771    static String[] splitString(String str, char sep) {
1772        int count = 1;
1773        int i = 0;
1774        while ((i=str.indexOf(sep, i)) >= 0) {
1775            count++;
1776            i++;
1777        }
1778
1779        String[] res = new String[count];
1780        i=0;
1781        count = 0;
1782        int lastI=0;
1783        while ((i=str.indexOf(sep, i)) >= 0) {
1784            res[count] = str.substring(lastI, i);
1785            count++;
1786            i++;
1787            lastI = i;
1788        }
1789        res[count] = str.substring(lastI, str.length());
1790        return res;
1791    }
1792
1793    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795                Context.DISPLAY_SERVICE);
1796        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1797    }
1798
1799    public PackageManagerService(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802                SystemClock.uptimeMillis());
1803
1804        if (mSdkVersion <= 0) {
1805            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1806        }
1807
1808        mContext = context;
1809        mFactoryTest = factoryTest;
1810        mOnlyCore = onlyCore;
1811        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812        mMetrics = new DisplayMetrics();
1813        mSettings = new Settings(mPackages);
1814        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1826
1827        // TODO: add a property to control this?
1828        long dexOptLRUThresholdInMinutes;
1829        if (mLazyDexOpt) {
1830            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1831        } else {
1832            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1833        }
1834        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1835
1836        String separateProcesses = SystemProperties.get("debug.separate_processes");
1837        if (separateProcesses != null && separateProcesses.length() > 0) {
1838            if ("*".equals(separateProcesses)) {
1839                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840                mSeparateProcesses = null;
1841                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1842            } else {
1843                mDefParseFlags = 0;
1844                mSeparateProcesses = separateProcesses.split(",");
1845                Slog.w(TAG, "Running with debug.separate_processes: "
1846                        + separateProcesses);
1847            }
1848        } else {
1849            mDefParseFlags = 0;
1850            mSeparateProcesses = null;
1851        }
1852
1853        mInstaller = installer;
1854        mPackageDexOptimizer = new PackageDexOptimizer(this);
1855        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1856
1857        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858                FgThread.get().getLooper());
1859
1860        getDefaultDisplayMetrics(context, mMetrics);
1861
1862        SystemConfig systemConfig = SystemConfig.getInstance();
1863        mGlobalGids = systemConfig.getGlobalGids();
1864        mSystemPermissions = systemConfig.getSystemPermissions();
1865        mAvailableFeatures = systemConfig.getAvailableFeatures();
1866
1867        synchronized (mInstallLock) {
1868        // writer
1869        synchronized (mPackages) {
1870            mHandlerThread = new ServiceThread(TAG,
1871                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872            mHandlerThread.start();
1873            mHandler = new PackageHandler(mHandlerThread.getLooper());
1874            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1875
1876            File dataDir = Environment.getDataDirectory();
1877            mAppDataDir = new File(dataDir, "data");
1878            mAppInstallDir = new File(dataDir, "app");
1879            mAppLib32InstallDir = new File(dataDir, "app-lib");
1880            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881            mUserAppDataDir = new File(dataDir, "user");
1882            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1883
1884            sUserManager = new UserManagerService(context, this,
1885                    mInstallLock, mPackages);
1886
1887            // Propagate permission configuration in to package manager.
1888            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889                    = systemConfig.getPermissions();
1890            for (int i=0; i<permConfig.size(); i++) {
1891                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892                BasePermission bp = mSettings.mPermissions.get(perm.name);
1893                if (bp == null) {
1894                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895                    mSettings.mPermissions.put(perm.name, bp);
1896                }
1897                if (perm.gids != null) {
1898                    bp.setGids(perm.gids, perm.perUser);
1899                }
1900            }
1901
1902            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903            for (int i=0; i<libConfig.size(); i++) {
1904                mSharedLibraries.put(libConfig.keyAt(i),
1905                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1906            }
1907
1908            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1909
1910            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911                    mSdkVersion, mOnlyCore);
1912
1913            String customResolverActivity = Resources.getSystem().getString(
1914                    R.string.config_customResolverActivity);
1915            if (TextUtils.isEmpty(customResolverActivity)) {
1916                customResolverActivity = null;
1917            } else {
1918                mCustomResolverComponentName = ComponentName.unflattenFromString(
1919                        customResolverActivity);
1920            }
1921
1922            long startTime = SystemClock.uptimeMillis();
1923
1924            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1925                    startTime);
1926
1927            // Set flag to monitor and not change apk file paths when
1928            // scanning install directories.
1929            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1930
1931            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1932
1933            /**
1934             * Add everything in the in the boot class path to the
1935             * list of process files because dexopt will have been run
1936             * if necessary during zygote startup.
1937             */
1938            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1940
1941            if (bootClassPath != null) {
1942                String[] bootClassPathElements = splitString(bootClassPath, ':');
1943                for (String element : bootClassPathElements) {
1944                    alreadyDexOpted.add(element);
1945                }
1946            } else {
1947                Slog.w(TAG, "No BOOTCLASSPATH found!");
1948            }
1949
1950            if (systemServerClassPath != null) {
1951                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952                for (String element : systemServerClassPathElements) {
1953                    alreadyDexOpted.add(element);
1954                }
1955            } else {
1956                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1957            }
1958
1959            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960            final String[] dexCodeInstructionSets =
1961                    getDexCodeInstructionSets(
1962                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1963
1964            /**
1965             * Ensure all external libraries have had dexopt run on them.
1966             */
1967            if (mSharedLibraries.size() > 0) {
1968                // NOTE: For now, we're compiling these system "shared libraries"
1969                // (and framework jars) into all available architectures. It's possible
1970                // to compile them only when we come across an app that uses them (there's
1971                // already logic for that in scanPackageLI) but that adds some complexity.
1972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974                        final String lib = libEntry.path;
1975                        if (lib == null) {
1976                            continue;
1977                        }
1978
1979                        try {
1980                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982                                alreadyDexOpted.add(lib);
1983                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
1984                            }
1985                        } catch (FileNotFoundException e) {
1986                            Slog.w(TAG, "Library not found: " + lib);
1987                        } catch (IOException e) {
1988                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1989                                    + e.getMessage());
1990                        }
1991                    }
1992                }
1993            }
1994
1995            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1996
1997            // Gross hack for now: we know this file doesn't contain any
1998            // code, so don't dexopt it to avoid the resulting log spew.
1999            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2000
2001            // Gross hack for now: we know this file is only part of
2002            // the boot class path for art, so don't dexopt it to
2003            // avoid the resulting log spew.
2004            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2005
2006            /**
2007             * There are a number of commands implemented in Java, which
2008             * we currently need to do the dexopt on so that they can be
2009             * run from a non-root shell.
2010             */
2011            String[] frameworkFiles = frameworkDir.list();
2012            if (frameworkFiles != null) {
2013                // TODO: We could compile these only for the most preferred ABI. We should
2014                // first double check that the dex files for these commands are not referenced
2015                // by other system apps.
2016                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2017                    for (int i=0; i<frameworkFiles.length; i++) {
2018                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2019                        String path = libPath.getPath();
2020                        // Skip the file if we already did it.
2021                        if (alreadyDexOpted.contains(path)) {
2022                            continue;
2023                        }
2024                        // Skip the file if it is not a type we want to dexopt.
2025                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2026                            continue;
2027                        }
2028                        try {
2029                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2030                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2031                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
2032                            }
2033                        } catch (FileNotFoundException e) {
2034                            Slog.w(TAG, "Jar not found: " + path);
2035                        } catch (IOException e) {
2036                            Slog.w(TAG, "Exception reading jar: " + path, e);
2037                        }
2038                    }
2039                }
2040            }
2041
2042            final VersionInfo ver = mSettings.getInternalVersion();
2043            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2044            // when upgrading from pre-M, promote system app permissions from install to runtime
2045            mPromoteSystemApps =
2046                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2047
2048            // save off the names of pre-existing system packages prior to scanning; we don't
2049            // want to automatically grant runtime permissions for new system apps
2050            if (mPromoteSystemApps) {
2051                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2052                while (pkgSettingIter.hasNext()) {
2053                    PackageSetting ps = pkgSettingIter.next();
2054                    if (isSystemApp(ps)) {
2055                        mExistingSystemPackages.add(ps.name);
2056                    }
2057                }
2058            }
2059
2060            // Collect vendor overlay packages.
2061            // (Do this before scanning any apps.)
2062            // For security and version matching reason, only consider
2063            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2064            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2065            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2066                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2067
2068            // Find base frameworks (resource packages without code).
2069            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2070                    | PackageParser.PARSE_IS_SYSTEM_DIR
2071                    | PackageParser.PARSE_IS_PRIVILEGED,
2072                    scanFlags | SCAN_NO_DEX, 0);
2073
2074            // Collected privileged system packages.
2075            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2076            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2077                    | PackageParser.PARSE_IS_SYSTEM_DIR
2078                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2079
2080            // Collect ordinary system packages.
2081            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2082            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2083                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2084
2085            // Collect all vendor packages.
2086            File vendorAppDir = new File("/vendor/app");
2087            try {
2088                vendorAppDir = vendorAppDir.getCanonicalFile();
2089            } catch (IOException e) {
2090                // failed to look up canonical path, continue with original one
2091            }
2092            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2093                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2094
2095            // Collect all OEM packages.
2096            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2097            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2098                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2099
2100            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2101            mInstaller.moveFiles();
2102
2103            // Prune any system packages that no longer exist.
2104            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2105            if (!mOnlyCore) {
2106                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2107                while (psit.hasNext()) {
2108                    PackageSetting ps = psit.next();
2109
2110                    /*
2111                     * If this is not a system app, it can't be a
2112                     * disable system app.
2113                     */
2114                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2115                        continue;
2116                    }
2117
2118                    /*
2119                     * If the package is scanned, it's not erased.
2120                     */
2121                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2122                    if (scannedPkg != null) {
2123                        /*
2124                         * If the system app is both scanned and in the
2125                         * disabled packages list, then it must have been
2126                         * added via OTA. Remove it from the currently
2127                         * scanned package so the previously user-installed
2128                         * application can be scanned.
2129                         */
2130                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2131                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2132                                    + ps.name + "; removing system app.  Last known codePath="
2133                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2134                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2135                                    + scannedPkg.mVersionCode);
2136                            removePackageLI(ps, true);
2137                            mExpectingBetter.put(ps.name, ps.codePath);
2138                        }
2139
2140                        continue;
2141                    }
2142
2143                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2144                        psit.remove();
2145                        logCriticalInfo(Log.WARN, "System package " + ps.name
2146                                + " no longer exists; wiping its data");
2147                        removeDataDirsLI(null, ps.name);
2148                    } else {
2149                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2150                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2151                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2152                        }
2153                    }
2154                }
2155            }
2156
2157            //look for any incomplete package installations
2158            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2159            //clean up list
2160            for(int i = 0; i < deletePkgsList.size(); i++) {
2161                //clean up here
2162                cleanupInstallFailedPackage(deletePkgsList.get(i));
2163            }
2164            //delete tmp files
2165            deleteTempPackageFiles();
2166
2167            // Remove any shared userIDs that have no associated packages
2168            mSettings.pruneSharedUsersLPw();
2169
2170            if (!mOnlyCore) {
2171                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2172                        SystemClock.uptimeMillis());
2173                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2174
2175                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2176                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2177
2178                /**
2179                 * Remove disable package settings for any updated system
2180                 * apps that were removed via an OTA. If they're not a
2181                 * previously-updated app, remove them completely.
2182                 * Otherwise, just revoke their system-level permissions.
2183                 */
2184                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2185                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2186                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2187
2188                    String msg;
2189                    if (deletedPkg == null) {
2190                        msg = "Updated system package " + deletedAppName
2191                                + " no longer exists; wiping its data";
2192                        removeDataDirsLI(null, deletedAppName);
2193                    } else {
2194                        msg = "Updated system app + " + deletedAppName
2195                                + " no longer present; removing system privileges for "
2196                                + deletedAppName;
2197
2198                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2199
2200                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2201                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2202                    }
2203                    logCriticalInfo(Log.WARN, msg);
2204                }
2205
2206                /**
2207                 * Make sure all system apps that we expected to appear on
2208                 * the userdata partition actually showed up. If they never
2209                 * appeared, crawl back and revive the system version.
2210                 */
2211                for (int i = 0; i < mExpectingBetter.size(); i++) {
2212                    final String packageName = mExpectingBetter.keyAt(i);
2213                    if (!mPackages.containsKey(packageName)) {
2214                        final File scanFile = mExpectingBetter.valueAt(i);
2215
2216                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2217                                + " but never showed up; reverting to system");
2218
2219                        final int reparseFlags;
2220                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2221                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2222                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2223                                    | PackageParser.PARSE_IS_PRIVILEGED;
2224                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2225                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2226                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2227                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2228                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2229                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2230                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2231                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2232                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2233                        } else {
2234                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2235                            continue;
2236                        }
2237
2238                        mSettings.enableSystemPackageLPw(packageName);
2239
2240                        try {
2241                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2242                        } catch (PackageManagerException e) {
2243                            Slog.e(TAG, "Failed to parse original system package: "
2244                                    + e.getMessage());
2245                        }
2246                    }
2247                }
2248            }
2249            mExpectingBetter.clear();
2250
2251            // Now that we know all of the shared libraries, update all clients to have
2252            // the correct library paths.
2253            updateAllSharedLibrariesLPw();
2254
2255            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2256                // NOTE: We ignore potential failures here during a system scan (like
2257                // the rest of the commands above) because there's precious little we
2258                // can do about it. A settings error is reported, though.
2259                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2260                        false /* force dexopt */, false /* defer dexopt */,
2261                        false /* boot complete */);
2262            }
2263
2264            // Now that we know all the packages we are keeping,
2265            // read and update their last usage times.
2266            mPackageUsage.readLP();
2267
2268            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2269                    SystemClock.uptimeMillis());
2270            Slog.i(TAG, "Time to scan packages: "
2271                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2272                    + " seconds");
2273
2274            // If the platform SDK has changed since the last time we booted,
2275            // we need to re-grant app permission to catch any new ones that
2276            // appear.  This is really a hack, and means that apps can in some
2277            // cases get permissions that the user didn't initially explicitly
2278            // allow...  it would be nice to have some better way to handle
2279            // this situation.
2280            int updateFlags = UPDATE_PERMISSIONS_ALL;
2281            if (ver.sdkVersion != mSdkVersion) {
2282                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2283                        + mSdkVersion + "; regranting permissions for internal storage");
2284                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2285            }
2286            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2287            ver.sdkVersion = mSdkVersion;
2288
2289            // If this is the first boot or an update from pre-M, and it is a normal
2290            // boot, then we need to initialize the default preferred apps across
2291            // all defined users.
2292            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2293                for (UserInfo user : sUserManager.getUsers(true)) {
2294                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2295                    applyFactoryDefaultBrowserLPw(user.id);
2296                    primeDomainVerificationsLPw(user.id);
2297                }
2298            }
2299
2300            // If this is first boot after an OTA, and a normal boot, then
2301            // we need to clear code cache directories.
2302            if (mIsUpgrade && !onlyCore) {
2303                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2304                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2305                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2306                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2307                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2308                    }
2309                }
2310                ver.fingerprint = Build.FINGERPRINT;
2311            }
2312
2313            checkDefaultBrowser();
2314
2315            // clear only after permissions and other defaults have been updated
2316            mExistingSystemPackages.clear();
2317            mPromoteSystemApps = false;
2318
2319            // All the changes are done during package scanning.
2320            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2321
2322            // can downgrade to reader
2323            mSettings.writeLPr();
2324
2325            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2326                    SystemClock.uptimeMillis());
2327
2328            mRequiredVerifierPackage = getRequiredVerifierLPr();
2329            mRequiredInstallerPackage = getRequiredInstallerLPr();
2330
2331            mInstallerService = new PackageInstallerService(context, this);
2332
2333            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2334            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2335                    mIntentFilterVerifierComponent);
2336
2337        } // synchronized (mPackages)
2338        } // synchronized (mInstallLock)
2339
2340        // Now after opening every single application zip, make sure they
2341        // are all flushed.  Not really needed, but keeps things nice and
2342        // tidy.
2343        Runtime.getRuntime().gc();
2344
2345        // Expose private service for system components to use.
2346        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2347    }
2348
2349    @Override
2350    public boolean isFirstBoot() {
2351        return !mRestoredSettings;
2352    }
2353
2354    @Override
2355    public boolean isOnlyCoreApps() {
2356        return mOnlyCore;
2357    }
2358
2359    @Override
2360    public boolean isUpgrade() {
2361        return mIsUpgrade;
2362    }
2363
2364    private String getRequiredVerifierLPr() {
2365        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2366        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2367                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2368
2369        String requiredVerifier = null;
2370
2371        final int N = receivers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = receivers.get(i);
2374
2375            if (info.activityInfo == null) {
2376                continue;
2377            }
2378
2379            final String packageName = info.activityInfo.packageName;
2380
2381            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2382                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2383                continue;
2384            }
2385
2386            if (requiredVerifier != null) {
2387                throw new RuntimeException("There can be only one required verifier");
2388            }
2389
2390            requiredVerifier = packageName;
2391        }
2392
2393        return requiredVerifier;
2394    }
2395
2396    private String getRequiredInstallerLPr() {
2397        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2398        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2399        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2400
2401        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2402                PACKAGE_MIME_TYPE, 0, 0);
2403
2404        String requiredInstaller = null;
2405
2406        final int N = installers.size();
2407        for (int i = 0; i < N; i++) {
2408            final ResolveInfo info = installers.get(i);
2409            final String packageName = info.activityInfo.packageName;
2410
2411            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2412                continue;
2413            }
2414
2415            if (requiredInstaller != null) {
2416                throw new RuntimeException("There must be one required installer");
2417            }
2418
2419            requiredInstaller = packageName;
2420        }
2421
2422        if (requiredInstaller == null) {
2423            throw new RuntimeException("There must be one required installer");
2424        }
2425
2426        return requiredInstaller;
2427    }
2428
2429    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2430        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2431        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2432                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2433
2434        ComponentName verifierComponentName = null;
2435
2436        int priority = -1000;
2437        final int N = receivers.size();
2438        for (int i = 0; i < N; i++) {
2439            final ResolveInfo info = receivers.get(i);
2440
2441            if (info.activityInfo == null) {
2442                continue;
2443            }
2444
2445            final String packageName = info.activityInfo.packageName;
2446
2447            final PackageSetting ps = mSettings.mPackages.get(packageName);
2448            if (ps == null) {
2449                continue;
2450            }
2451
2452            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2453                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2454                continue;
2455            }
2456
2457            // Select the IntentFilterVerifier with the highest priority
2458            if (priority < info.priority) {
2459                priority = info.priority;
2460                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2461                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2462                        + verifierComponentName + " with priority: " + info.priority);
2463            }
2464        }
2465
2466        return verifierComponentName;
2467    }
2468
2469    private void primeDomainVerificationsLPw(int userId) {
2470        if (DEBUG_DOMAIN_VERIFICATION) {
2471            Slog.d(TAG, "Priming domain verifications in user " + userId);
2472        }
2473
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        ArraySet<String> packages = systemConfig.getLinkedApps();
2476        ArraySet<String> domains = new ArraySet<String>();
2477
2478        for (String packageName : packages) {
2479            PackageParser.Package pkg = mPackages.get(packageName);
2480            if (pkg != null) {
2481                if (!pkg.isSystemApp()) {
2482                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2483                    continue;
2484                }
2485
2486                domains.clear();
2487                for (PackageParser.Activity a : pkg.activities) {
2488                    for (ActivityIntentInfo filter : a.intents) {
2489                        if (hasValidDomains(filter)) {
2490                            domains.addAll(filter.getHostsList());
2491                        }
2492                    }
2493                }
2494
2495                if (domains.size() > 0) {
2496                    if (DEBUG_DOMAIN_VERIFICATION) {
2497                        Slog.v(TAG, "      + " + packageName);
2498                    }
2499                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2500                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2501                    // and then 'always' in the per-user state actually used for intent resolution.
2502                    final IntentFilterVerificationInfo ivi;
2503                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2504                            new ArrayList<String>(domains));
2505                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2506                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2507                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2508                } else {
2509                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2510                            + "' does not handle web links");
2511                }
2512            } else {
2513                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2514            }
2515        }
2516
2517        scheduleWritePackageRestrictionsLocked(userId);
2518        scheduleWriteSettingsLocked();
2519    }
2520
2521    private void applyFactoryDefaultBrowserLPw(int userId) {
2522        // The default browser app's package name is stored in a string resource,
2523        // with a product-specific overlay used for vendor customization.
2524        String browserPkg = mContext.getResources().getString(
2525                com.android.internal.R.string.default_browser);
2526        if (!TextUtils.isEmpty(browserPkg)) {
2527            // non-empty string => required to be a known package
2528            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2529            if (ps == null) {
2530                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2531                browserPkg = null;
2532            } else {
2533                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2534            }
2535        }
2536
2537        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2538        // default.  If there's more than one, just leave everything alone.
2539        if (browserPkg == null) {
2540            calculateDefaultBrowserLPw(userId);
2541        }
2542    }
2543
2544    private void calculateDefaultBrowserLPw(int userId) {
2545        List<String> allBrowsers = resolveAllBrowserApps(userId);
2546        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2547        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2548    }
2549
2550    private List<String> resolveAllBrowserApps(int userId) {
2551        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2552        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2553                PackageManager.MATCH_ALL, userId);
2554
2555        final int count = list.size();
2556        List<String> result = new ArrayList<String>(count);
2557        for (int i=0; i<count; i++) {
2558            ResolveInfo info = list.get(i);
2559            if (info.activityInfo == null
2560                    || !info.handleAllWebDataURI
2561                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2562                    || result.contains(info.activityInfo.packageName)) {
2563                continue;
2564            }
2565            result.add(info.activityInfo.packageName);
2566        }
2567
2568        return result;
2569    }
2570
2571    private boolean packageIsBrowser(String packageName, int userId) {
2572        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2573                PackageManager.MATCH_ALL, userId);
2574        final int N = list.size();
2575        for (int i = 0; i < N; i++) {
2576            ResolveInfo info = list.get(i);
2577            if (packageName.equals(info.activityInfo.packageName)) {
2578                return true;
2579            }
2580        }
2581        return false;
2582    }
2583
2584    private void checkDefaultBrowser() {
2585        final int myUserId = UserHandle.myUserId();
2586        final String packageName = getDefaultBrowserPackageName(myUserId);
2587        if (packageName != null) {
2588            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2589            if (info == null) {
2590                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2591                synchronized (mPackages) {
2592                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2593                }
2594            }
2595        }
2596    }
2597
2598    @Override
2599    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2600            throws RemoteException {
2601        try {
2602            return super.onTransact(code, data, reply, flags);
2603        } catch (RuntimeException e) {
2604            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2605                Slog.wtf(TAG, "Package Manager Crash", e);
2606            }
2607            throw e;
2608        }
2609    }
2610
2611    void cleanupInstallFailedPackage(PackageSetting ps) {
2612        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2613
2614        removeDataDirsLI(ps.volumeUuid, ps.name);
2615        if (ps.codePath != null) {
2616            if (ps.codePath.isDirectory()) {
2617                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2618            } else {
2619                ps.codePath.delete();
2620            }
2621        }
2622        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2623            if (ps.resourcePath.isDirectory()) {
2624                FileUtils.deleteContents(ps.resourcePath);
2625            }
2626            ps.resourcePath.delete();
2627        }
2628        mSettings.removePackageLPw(ps.name);
2629    }
2630
2631    static int[] appendInts(int[] cur, int[] add) {
2632        if (add == null) return cur;
2633        if (cur == null) return add;
2634        final int N = add.length;
2635        for (int i=0; i<N; i++) {
2636            cur = appendInt(cur, add[i]);
2637        }
2638        return cur;
2639    }
2640
2641    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        final PackageSetting ps = (PackageSetting) p.mExtras;
2644        if (ps == null) {
2645            return null;
2646        }
2647
2648        final PermissionsState permissionsState = ps.getPermissionsState();
2649
2650        final int[] gids = permissionsState.computeGids(userId);
2651        final Set<String> permissions = permissionsState.getPermissions(userId);
2652        final PackageUserState state = ps.readUserState(userId);
2653
2654        return PackageParser.generatePackageInfo(p, gids, flags,
2655                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2656    }
2657
2658    @Override
2659    public boolean isPackageFrozen(String packageName) {
2660        synchronized (mPackages) {
2661            final PackageSetting ps = mSettings.mPackages.get(packageName);
2662            if (ps != null) {
2663                return ps.frozen;
2664            }
2665        }
2666        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2667        return true;
2668    }
2669
2670    @Override
2671    public boolean isPackageAvailable(String packageName, int userId) {
2672        if (!sUserManager.exists(userId)) return false;
2673        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2674        synchronized (mPackages) {
2675            PackageParser.Package p = mPackages.get(packageName);
2676            if (p != null) {
2677                final PackageSetting ps = (PackageSetting) p.mExtras;
2678                if (ps != null) {
2679                    final PackageUserState state = ps.readUserState(userId);
2680                    if (state != null) {
2681                        return PackageParser.isAvailable(state);
2682                    }
2683                }
2684            }
2685        }
2686        return false;
2687    }
2688
2689    @Override
2690    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2691        if (!sUserManager.exists(userId)) return null;
2692        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2693        // reader
2694        synchronized (mPackages) {
2695            PackageParser.Package p = mPackages.get(packageName);
2696            if (DEBUG_PACKAGE_INFO)
2697                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2698            if (p != null) {
2699                return generatePackageInfo(p, flags, userId);
2700            }
2701            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2702                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2703            }
2704        }
2705        return null;
2706    }
2707
2708    @Override
2709    public String[] currentToCanonicalPackageNames(String[] names) {
2710        String[] out = new String[names.length];
2711        // reader
2712        synchronized (mPackages) {
2713            for (int i=names.length-1; i>=0; i--) {
2714                PackageSetting ps = mSettings.mPackages.get(names[i]);
2715                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2716            }
2717        }
2718        return out;
2719    }
2720
2721    @Override
2722    public String[] canonicalToCurrentPackageNames(String[] names) {
2723        String[] out = new String[names.length];
2724        // reader
2725        synchronized (mPackages) {
2726            for (int i=names.length-1; i>=0; i--) {
2727                String cur = mSettings.mRenamedPackages.get(names[i]);
2728                out[i] = cur != null ? cur : names[i];
2729            }
2730        }
2731        return out;
2732    }
2733
2734    @Override
2735    public int getPackageUid(String packageName, int userId) {
2736        return getPackageUidEtc(packageName, 0, userId);
2737    }
2738
2739    @Override
2740    public int getPackageUidEtc(String packageName, int flags, int userId) {
2741        if (!sUserManager.exists(userId)) return -1;
2742        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2743
2744        // reader
2745        synchronized (mPackages) {
2746            final PackageParser.Package p = mPackages.get(packageName);
2747            if (p != null) {
2748                return UserHandle.getUid(userId, p.applicationInfo.uid);
2749            }
2750            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2751                final PackageSetting ps = mSettings.mPackages.get(packageName);
2752                if (ps != null) {
2753                    return UserHandle.getUid(userId, ps.appId);
2754                }
2755            }
2756        }
2757
2758        return -1;
2759    }
2760
2761    @Override
2762    public int[] getPackageGids(String packageName, int userId) {
2763        return getPackageGidsEtc(packageName, 0, userId);
2764    }
2765
2766    @Override
2767    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2768        if (!sUserManager.exists(userId)) {
2769            return null;
2770        }
2771
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2773                "getPackageGids");
2774
2775        // reader
2776        synchronized (mPackages) {
2777            final PackageParser.Package p = mPackages.get(packageName);
2778            if (p != null) {
2779                PackageSetting ps = (PackageSetting) p.mExtras;
2780                return ps.getPermissionsState().computeGids(userId);
2781            }
2782            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2783                final PackageSetting ps = mSettings.mPackages.get(packageName);
2784                if (ps != null) {
2785                    return ps.getPermissionsState().computeGids(userId);
2786                }
2787            }
2788        }
2789
2790        return null;
2791    }
2792
2793    static PermissionInfo generatePermissionInfo(
2794            BasePermission bp, int flags) {
2795        if (bp.perm != null) {
2796            return PackageParser.generatePermissionInfo(bp.perm, flags);
2797        }
2798        PermissionInfo pi = new PermissionInfo();
2799        pi.name = bp.name;
2800        pi.packageName = bp.sourcePackage;
2801        pi.nonLocalizedLabel = bp.name;
2802        pi.protectionLevel = bp.protectionLevel;
2803        return pi;
2804    }
2805
2806    @Override
2807    public PermissionInfo getPermissionInfo(String name, int flags) {
2808        // reader
2809        synchronized (mPackages) {
2810            final BasePermission p = mSettings.mPermissions.get(name);
2811            if (p != null) {
2812                return generatePermissionInfo(p, flags);
2813            }
2814            return null;
2815        }
2816    }
2817
2818    @Override
2819    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2820        // reader
2821        synchronized (mPackages) {
2822            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2823            for (BasePermission p : mSettings.mPermissions.values()) {
2824                if (group == null) {
2825                    if (p.perm == null || p.perm.info.group == null) {
2826                        out.add(generatePermissionInfo(p, flags));
2827                    }
2828                } else {
2829                    if (p.perm != null && group.equals(p.perm.info.group)) {
2830                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2831                    }
2832                }
2833            }
2834
2835            if (out.size() > 0) {
2836                return out;
2837            }
2838            return mPermissionGroups.containsKey(group) ? out : null;
2839        }
2840    }
2841
2842    @Override
2843    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2844        // reader
2845        synchronized (mPackages) {
2846            return PackageParser.generatePermissionGroupInfo(
2847                    mPermissionGroups.get(name), flags);
2848        }
2849    }
2850
2851    @Override
2852    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2853        // reader
2854        synchronized (mPackages) {
2855            final int N = mPermissionGroups.size();
2856            ArrayList<PermissionGroupInfo> out
2857                    = new ArrayList<PermissionGroupInfo>(N);
2858            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2859                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2860            }
2861            return out;
2862        }
2863    }
2864
2865    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2866            int userId) {
2867        if (!sUserManager.exists(userId)) return null;
2868        PackageSetting ps = mSettings.mPackages.get(packageName);
2869        if (ps != null) {
2870            if (ps.pkg == null) {
2871                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2872                        flags, userId);
2873                if (pInfo != null) {
2874                    return pInfo.applicationInfo;
2875                }
2876                return null;
2877            }
2878            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2879                    ps.readUserState(userId), userId);
2880        }
2881        return null;
2882    }
2883
2884    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2885            int userId) {
2886        if (!sUserManager.exists(userId)) return null;
2887        PackageSetting ps = mSettings.mPackages.get(packageName);
2888        if (ps != null) {
2889            PackageParser.Package pkg = ps.pkg;
2890            if (pkg == null) {
2891                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2892                    return null;
2893                }
2894                // Only data remains, so we aren't worried about code paths
2895                pkg = new PackageParser.Package(packageName);
2896                pkg.applicationInfo.packageName = packageName;
2897                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2898                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2899                pkg.applicationInfo.dataDir = Environment
2900                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2901                        .getAbsolutePath();
2902                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2903                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2904            }
2905            return generatePackageInfo(pkg, flags, userId);
2906        }
2907        return null;
2908    }
2909
2910    @Override
2911    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2912        if (!sUserManager.exists(userId)) return null;
2913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2914        // writer
2915        synchronized (mPackages) {
2916            PackageParser.Package p = mPackages.get(packageName);
2917            if (DEBUG_PACKAGE_INFO) Log.v(
2918                    TAG, "getApplicationInfo " + packageName
2919                    + ": " + p);
2920            if (p != null) {
2921                PackageSetting ps = mSettings.mPackages.get(packageName);
2922                if (ps == null) return null;
2923                // Note: isEnabledLP() does not apply here - always return info
2924                return PackageParser.generateApplicationInfo(
2925                        p, flags, ps.readUserState(userId), userId);
2926            }
2927            if ("android".equals(packageName)||"system".equals(packageName)) {
2928                return mAndroidApplication;
2929            }
2930            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2931                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2932            }
2933        }
2934        return null;
2935    }
2936
2937    @Override
2938    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2939            final IPackageDataObserver observer) {
2940        mContext.enforceCallingOrSelfPermission(
2941                android.Manifest.permission.CLEAR_APP_CACHE, null);
2942        // Queue up an async operation since clearing cache may take a little while.
2943        mHandler.post(new Runnable() {
2944            public void run() {
2945                mHandler.removeCallbacks(this);
2946                int retCode = -1;
2947                synchronized (mInstallLock) {
2948                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2949                    if (retCode < 0) {
2950                        Slog.w(TAG, "Couldn't clear application caches");
2951                    }
2952                }
2953                if (observer != null) {
2954                    try {
2955                        observer.onRemoveCompleted(null, (retCode >= 0));
2956                    } catch (RemoteException e) {
2957                        Slog.w(TAG, "RemoveException when invoking call back");
2958                    }
2959                }
2960            }
2961        });
2962    }
2963
2964    @Override
2965    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2966            final IntentSender pi) {
2967        mContext.enforceCallingOrSelfPermission(
2968                android.Manifest.permission.CLEAR_APP_CACHE, null);
2969        // Queue up an async operation since clearing cache may take a little while.
2970        mHandler.post(new Runnable() {
2971            public void run() {
2972                mHandler.removeCallbacks(this);
2973                int retCode = -1;
2974                synchronized (mInstallLock) {
2975                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2976                    if (retCode < 0) {
2977                        Slog.w(TAG, "Couldn't clear application caches");
2978                    }
2979                }
2980                if(pi != null) {
2981                    try {
2982                        // Callback via pending intent
2983                        int code = (retCode >= 0) ? 1 : 0;
2984                        pi.sendIntent(null, code, null,
2985                                null, null);
2986                    } catch (SendIntentException e1) {
2987                        Slog.i(TAG, "Failed to send pending intent");
2988                    }
2989                }
2990            }
2991        });
2992    }
2993
2994    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2995        synchronized (mInstallLock) {
2996            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2997                throw new IOException("Failed to free enough space");
2998            }
2999        }
3000    }
3001
3002    @Override
3003    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3004        if (!sUserManager.exists(userId)) return null;
3005        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3006        synchronized (mPackages) {
3007            PackageParser.Activity a = mActivities.mActivities.get(component);
3008
3009            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3010            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3011                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3012                if (ps == null) return null;
3013                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3014                        userId);
3015            }
3016            if (mResolveComponentName.equals(component)) {
3017                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3018                        new PackageUserState(), userId);
3019            }
3020        }
3021        return null;
3022    }
3023
3024    @Override
3025    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3026            String resolvedType) {
3027        synchronized (mPackages) {
3028            if (component.equals(mResolveComponentName)) {
3029                // The resolver supports EVERYTHING!
3030                return true;
3031            }
3032            PackageParser.Activity a = mActivities.mActivities.get(component);
3033            if (a == null) {
3034                return false;
3035            }
3036            for (int i=0; i<a.intents.size(); i++) {
3037                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3038                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3039                    return true;
3040                }
3041            }
3042            return false;
3043        }
3044    }
3045
3046    @Override
3047    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3048        if (!sUserManager.exists(userId)) return null;
3049        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3050        synchronized (mPackages) {
3051            PackageParser.Activity a = mReceivers.mActivities.get(component);
3052            if (DEBUG_PACKAGE_INFO) Log.v(
3053                TAG, "getReceiverInfo " + component + ": " + a);
3054            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3055                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3056                if (ps == null) return null;
3057                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3058                        userId);
3059            }
3060        }
3061        return null;
3062    }
3063
3064    @Override
3065    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3066        if (!sUserManager.exists(userId)) return null;
3067        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3068        synchronized (mPackages) {
3069            PackageParser.Service s = mServices.mServices.get(component);
3070            if (DEBUG_PACKAGE_INFO) Log.v(
3071                TAG, "getServiceInfo " + component + ": " + s);
3072            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3073                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3074                if (ps == null) return null;
3075                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3076                        userId);
3077            }
3078        }
3079        return null;
3080    }
3081
3082    @Override
3083    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3084        if (!sUserManager.exists(userId)) return null;
3085        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3086        synchronized (mPackages) {
3087            PackageParser.Provider p = mProviders.mProviders.get(component);
3088            if (DEBUG_PACKAGE_INFO) Log.v(
3089                TAG, "getProviderInfo " + component + ": " + p);
3090            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3091                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3092                if (ps == null) return null;
3093                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3094                        userId);
3095            }
3096        }
3097        return null;
3098    }
3099
3100    @Override
3101    public String[] getSystemSharedLibraryNames() {
3102        Set<String> libSet;
3103        synchronized (mPackages) {
3104            libSet = mSharedLibraries.keySet();
3105            int size = libSet.size();
3106            if (size > 0) {
3107                String[] libs = new String[size];
3108                libSet.toArray(libs);
3109                return libs;
3110            }
3111        }
3112        return null;
3113    }
3114
3115    /**
3116     * @hide
3117     */
3118    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3119        synchronized (mPackages) {
3120            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3121            if (lib != null && lib.apk != null) {
3122                return mPackages.get(lib.apk);
3123            }
3124        }
3125        return null;
3126    }
3127
3128    @Override
3129    public FeatureInfo[] getSystemAvailableFeatures() {
3130        Collection<FeatureInfo> featSet;
3131        synchronized (mPackages) {
3132            featSet = mAvailableFeatures.values();
3133            int size = featSet.size();
3134            if (size > 0) {
3135                FeatureInfo[] features = new FeatureInfo[size+1];
3136                featSet.toArray(features);
3137                FeatureInfo fi = new FeatureInfo();
3138                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3139                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3140                features[size] = fi;
3141                return features;
3142            }
3143        }
3144        return null;
3145    }
3146
3147    @Override
3148    public boolean hasSystemFeature(String name) {
3149        synchronized (mPackages) {
3150            return mAvailableFeatures.containsKey(name);
3151        }
3152    }
3153
3154    private void checkValidCaller(int uid, int userId) {
3155        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3156            return;
3157
3158        throw new SecurityException("Caller uid=" + uid
3159                + " is not privileged to communicate with user=" + userId);
3160    }
3161
3162    @Override
3163    public int checkPermission(String permName, String pkgName, int userId) {
3164        if (!sUserManager.exists(userId)) {
3165            return PackageManager.PERMISSION_DENIED;
3166        }
3167
3168        synchronized (mPackages) {
3169            final PackageParser.Package p = mPackages.get(pkgName);
3170            if (p != null && p.mExtras != null) {
3171                final PackageSetting ps = (PackageSetting) p.mExtras;
3172                final PermissionsState permissionsState = ps.getPermissionsState();
3173                if (permissionsState.hasPermission(permName, userId)) {
3174                    return PackageManager.PERMISSION_GRANTED;
3175                }
3176                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3177                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3178                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3179                    return PackageManager.PERMISSION_GRANTED;
3180                }
3181            }
3182        }
3183
3184        return PackageManager.PERMISSION_DENIED;
3185    }
3186
3187    @Override
3188    public int checkUidPermission(String permName, int uid) {
3189        final int userId = UserHandle.getUserId(uid);
3190
3191        if (!sUserManager.exists(userId)) {
3192            return PackageManager.PERMISSION_DENIED;
3193        }
3194
3195        synchronized (mPackages) {
3196            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3197            if (obj != null) {
3198                final SettingBase ps = (SettingBase) obj;
3199                final PermissionsState permissionsState = ps.getPermissionsState();
3200                if (permissionsState.hasPermission(permName, userId)) {
3201                    return PackageManager.PERMISSION_GRANTED;
3202                }
3203                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3204                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3205                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3206                    return PackageManager.PERMISSION_GRANTED;
3207                }
3208            } else {
3209                ArraySet<String> perms = mSystemPermissions.get(uid);
3210                if (perms != null) {
3211                    if (perms.contains(permName)) {
3212                        return PackageManager.PERMISSION_GRANTED;
3213                    }
3214                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3215                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3216                        return PackageManager.PERMISSION_GRANTED;
3217                    }
3218                }
3219            }
3220        }
3221
3222        return PackageManager.PERMISSION_DENIED;
3223    }
3224
3225    @Override
3226    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3227        if (UserHandle.getCallingUserId() != userId) {
3228            mContext.enforceCallingPermission(
3229                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3230                    "isPermissionRevokedByPolicy for user " + userId);
3231        }
3232
3233        if (checkPermission(permission, packageName, userId)
3234                == PackageManager.PERMISSION_GRANTED) {
3235            return false;
3236        }
3237
3238        final long identity = Binder.clearCallingIdentity();
3239        try {
3240            final int flags = getPermissionFlags(permission, packageName, userId);
3241            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3242        } finally {
3243            Binder.restoreCallingIdentity(identity);
3244        }
3245    }
3246
3247    @Override
3248    public String getPermissionControllerPackageName() {
3249        synchronized (mPackages) {
3250            return mRequiredInstallerPackage;
3251        }
3252    }
3253
3254    /**
3255     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3256     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3257     * @param checkShell TODO(yamasani):
3258     * @param message the message to log on security exception
3259     */
3260    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3261            boolean checkShell, String message) {
3262        if (userId < 0) {
3263            throw new IllegalArgumentException("Invalid userId " + userId);
3264        }
3265        if (checkShell) {
3266            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3267        }
3268        if (userId == UserHandle.getUserId(callingUid)) return;
3269        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3270            if (requireFullPermission) {
3271                mContext.enforceCallingOrSelfPermission(
3272                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3273            } else {
3274                try {
3275                    mContext.enforceCallingOrSelfPermission(
3276                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3277                } catch (SecurityException se) {
3278                    mContext.enforceCallingOrSelfPermission(
3279                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3280                }
3281            }
3282        }
3283    }
3284
3285    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3286        if (callingUid == Process.SHELL_UID) {
3287            if (userHandle >= 0
3288                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3289                throw new SecurityException("Shell does not have permission to access user "
3290                        + userHandle);
3291            } else if (userHandle < 0) {
3292                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3293                        + Debug.getCallers(3));
3294            }
3295        }
3296    }
3297
3298    private BasePermission findPermissionTreeLP(String permName) {
3299        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3300            if (permName.startsWith(bp.name) &&
3301                    permName.length() > bp.name.length() &&
3302                    permName.charAt(bp.name.length()) == '.') {
3303                return bp;
3304            }
3305        }
3306        return null;
3307    }
3308
3309    private BasePermission checkPermissionTreeLP(String permName) {
3310        if (permName != null) {
3311            BasePermission bp = findPermissionTreeLP(permName);
3312            if (bp != null) {
3313                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3314                    return bp;
3315                }
3316                throw new SecurityException("Calling uid "
3317                        + Binder.getCallingUid()
3318                        + " is not allowed to add to permission tree "
3319                        + bp.name + " owned by uid " + bp.uid);
3320            }
3321        }
3322        throw new SecurityException("No permission tree found for " + permName);
3323    }
3324
3325    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3326        if (s1 == null) {
3327            return s2 == null;
3328        }
3329        if (s2 == null) {
3330            return false;
3331        }
3332        if (s1.getClass() != s2.getClass()) {
3333            return false;
3334        }
3335        return s1.equals(s2);
3336    }
3337
3338    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3339        if (pi1.icon != pi2.icon) return false;
3340        if (pi1.logo != pi2.logo) return false;
3341        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3342        if (!compareStrings(pi1.name, pi2.name)) return false;
3343        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3344        // We'll take care of setting this one.
3345        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3346        // These are not currently stored in settings.
3347        //if (!compareStrings(pi1.group, pi2.group)) return false;
3348        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3349        //if (pi1.labelRes != pi2.labelRes) return false;
3350        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3351        return true;
3352    }
3353
3354    int permissionInfoFootprint(PermissionInfo info) {
3355        int size = info.name.length();
3356        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3357        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3358        return size;
3359    }
3360
3361    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3362        int size = 0;
3363        for (BasePermission perm : mSettings.mPermissions.values()) {
3364            if (perm.uid == tree.uid) {
3365                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3366            }
3367        }
3368        return size;
3369    }
3370
3371    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3372        // We calculate the max size of permissions defined by this uid and throw
3373        // if that plus the size of 'info' would exceed our stated maximum.
3374        if (tree.uid != Process.SYSTEM_UID) {
3375            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3376            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3377                throw new SecurityException("Permission tree size cap exceeded");
3378            }
3379        }
3380    }
3381
3382    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3383        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3384            throw new SecurityException("Label must be specified in permission");
3385        }
3386        BasePermission tree = checkPermissionTreeLP(info.name);
3387        BasePermission bp = mSettings.mPermissions.get(info.name);
3388        boolean added = bp == null;
3389        boolean changed = true;
3390        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3391        if (added) {
3392            enforcePermissionCapLocked(info, tree);
3393            bp = new BasePermission(info.name, tree.sourcePackage,
3394                    BasePermission.TYPE_DYNAMIC);
3395        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3396            throw new SecurityException(
3397                    "Not allowed to modify non-dynamic permission "
3398                    + info.name);
3399        } else {
3400            if (bp.protectionLevel == fixedLevel
3401                    && bp.perm.owner.equals(tree.perm.owner)
3402                    && bp.uid == tree.uid
3403                    && comparePermissionInfos(bp.perm.info, info)) {
3404                changed = false;
3405            }
3406        }
3407        bp.protectionLevel = fixedLevel;
3408        info = new PermissionInfo(info);
3409        info.protectionLevel = fixedLevel;
3410        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3411        bp.perm.info.packageName = tree.perm.info.packageName;
3412        bp.uid = tree.uid;
3413        if (added) {
3414            mSettings.mPermissions.put(info.name, bp);
3415        }
3416        if (changed) {
3417            if (!async) {
3418                mSettings.writeLPr();
3419            } else {
3420                scheduleWriteSettingsLocked();
3421            }
3422        }
3423        return added;
3424    }
3425
3426    @Override
3427    public boolean addPermission(PermissionInfo info) {
3428        synchronized (mPackages) {
3429            return addPermissionLocked(info, false);
3430        }
3431    }
3432
3433    @Override
3434    public boolean addPermissionAsync(PermissionInfo info) {
3435        synchronized (mPackages) {
3436            return addPermissionLocked(info, true);
3437        }
3438    }
3439
3440    @Override
3441    public void removePermission(String name) {
3442        synchronized (mPackages) {
3443            checkPermissionTreeLP(name);
3444            BasePermission bp = mSettings.mPermissions.get(name);
3445            if (bp != null) {
3446                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3447                    throw new SecurityException(
3448                            "Not allowed to modify non-dynamic permission "
3449                            + name);
3450                }
3451                mSettings.mPermissions.remove(name);
3452                mSettings.writeLPr();
3453            }
3454        }
3455    }
3456
3457    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3458            BasePermission bp) {
3459        int index = pkg.requestedPermissions.indexOf(bp.name);
3460        if (index == -1) {
3461            throw new SecurityException("Package " + pkg.packageName
3462                    + " has not requested permission " + bp.name);
3463        }
3464        if (!bp.isRuntime() && !bp.isDevelopment()) {
3465            throw new SecurityException("Permission " + bp.name
3466                    + " is not a changeable permission type");
3467        }
3468    }
3469
3470    @Override
3471    public void grantRuntimePermission(String packageName, String name, final int userId) {
3472        if (!sUserManager.exists(userId)) {
3473            Log.e(TAG, "No such user:" + userId);
3474            return;
3475        }
3476
3477        mContext.enforceCallingOrSelfPermission(
3478                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3479                "grantRuntimePermission");
3480
3481        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3482                "grantRuntimePermission");
3483
3484        final int uid;
3485        final SettingBase sb;
3486
3487        synchronized (mPackages) {
3488            final PackageParser.Package pkg = mPackages.get(packageName);
3489            if (pkg == null) {
3490                throw new IllegalArgumentException("Unknown package: " + packageName);
3491            }
3492
3493            final BasePermission bp = mSettings.mPermissions.get(name);
3494            if (bp == null) {
3495                throw new IllegalArgumentException("Unknown permission: " + name);
3496            }
3497
3498            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3499
3500            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3501            sb = (SettingBase) pkg.mExtras;
3502            if (sb == null) {
3503                throw new IllegalArgumentException("Unknown package: " + packageName);
3504            }
3505
3506            final PermissionsState permissionsState = sb.getPermissionsState();
3507
3508            final int flags = permissionsState.getPermissionFlags(name, userId);
3509            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3510                throw new SecurityException("Cannot grant system fixed permission: "
3511                        + name + " for package: " + packageName);
3512            }
3513
3514            if (bp.isDevelopment()) {
3515                // Development permissions must be handled specially, since they are not
3516                // normal runtime permissions.  For now they apply to all users.
3517                if (permissionsState.grantInstallPermission(bp) !=
3518                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3519                    scheduleWriteSettingsLocked();
3520                }
3521                return;
3522            }
3523
3524            final int result = permissionsState.grantRuntimePermission(bp, userId);
3525            switch (result) {
3526                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3527                    return;
3528                }
3529
3530                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3531                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3532                    mHandler.post(new Runnable() {
3533                        @Override
3534                        public void run() {
3535                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3536                        }
3537                    });
3538                }
3539                break;
3540            }
3541
3542            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3543
3544            // Not critical if that is lost - app has to request again.
3545            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3546        }
3547
3548        // Only need to do this if user is initialized. Otherwise it's a new user
3549        // and there are no processes running as the user yet and there's no need
3550        // to make an expensive call to remount processes for the changed permissions.
3551        if (READ_EXTERNAL_STORAGE.equals(name)
3552                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3553            final long token = Binder.clearCallingIdentity();
3554            try {
3555                if (sUserManager.isInitialized(userId)) {
3556                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3557                            MountServiceInternal.class);
3558                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3559                }
3560            } finally {
3561                Binder.restoreCallingIdentity(token);
3562            }
3563        }
3564    }
3565
3566    @Override
3567    public void revokeRuntimePermission(String packageName, String name, int userId) {
3568        if (!sUserManager.exists(userId)) {
3569            Log.e(TAG, "No such user:" + userId);
3570            return;
3571        }
3572
3573        mContext.enforceCallingOrSelfPermission(
3574                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3575                "revokeRuntimePermission");
3576
3577        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3578                "revokeRuntimePermission");
3579
3580        final int appId;
3581
3582        synchronized (mPackages) {
3583            final PackageParser.Package pkg = mPackages.get(packageName);
3584            if (pkg == null) {
3585                throw new IllegalArgumentException("Unknown package: " + packageName);
3586            }
3587
3588            final BasePermission bp = mSettings.mPermissions.get(name);
3589            if (bp == null) {
3590                throw new IllegalArgumentException("Unknown permission: " + name);
3591            }
3592
3593            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3594
3595            SettingBase sb = (SettingBase) pkg.mExtras;
3596            if (sb == null) {
3597                throw new IllegalArgumentException("Unknown package: " + packageName);
3598            }
3599
3600            final PermissionsState permissionsState = sb.getPermissionsState();
3601
3602            final int flags = permissionsState.getPermissionFlags(name, userId);
3603            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3604                throw new SecurityException("Cannot revoke system fixed permission: "
3605                        + name + " for package: " + packageName);
3606            }
3607
3608            if (bp.isDevelopment()) {
3609                // Development permissions must be handled specially, since they are not
3610                // normal runtime permissions.  For now they apply to all users.
3611                if (permissionsState.revokeInstallPermission(bp) !=
3612                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3613                    scheduleWriteSettingsLocked();
3614                }
3615                return;
3616            }
3617
3618            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3619                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3620                return;
3621            }
3622
3623            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3624
3625            // Critical, after this call app should never have the permission.
3626            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3627
3628            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3629        }
3630
3631        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3632    }
3633
3634    @Override
3635    public void resetRuntimePermissions() {
3636        mContext.enforceCallingOrSelfPermission(
3637                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3638                "revokeRuntimePermission");
3639
3640        int callingUid = Binder.getCallingUid();
3641        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3642            mContext.enforceCallingOrSelfPermission(
3643                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3644                    "resetRuntimePermissions");
3645        }
3646
3647        synchronized (mPackages) {
3648            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3649            for (int userId : UserManagerService.getInstance().getUserIds()) {
3650                final int packageCount = mPackages.size();
3651                for (int i = 0; i < packageCount; i++) {
3652                    PackageParser.Package pkg = mPackages.valueAt(i);
3653                    if (!(pkg.mExtras instanceof PackageSetting)) {
3654                        continue;
3655                    }
3656                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3657                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3658                }
3659            }
3660        }
3661    }
3662
3663    @Override
3664    public int getPermissionFlags(String name, String packageName, int userId) {
3665        if (!sUserManager.exists(userId)) {
3666            return 0;
3667        }
3668
3669        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3670
3671        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3672                "getPermissionFlags");
3673
3674        synchronized (mPackages) {
3675            final PackageParser.Package pkg = mPackages.get(packageName);
3676            if (pkg == null) {
3677                throw new IllegalArgumentException("Unknown package: " + packageName);
3678            }
3679
3680            final BasePermission bp = mSettings.mPermissions.get(name);
3681            if (bp == null) {
3682                throw new IllegalArgumentException("Unknown permission: " + name);
3683            }
3684
3685            SettingBase sb = (SettingBase) pkg.mExtras;
3686            if (sb == null) {
3687                throw new IllegalArgumentException("Unknown package: " + packageName);
3688            }
3689
3690            PermissionsState permissionsState = sb.getPermissionsState();
3691            return permissionsState.getPermissionFlags(name, userId);
3692        }
3693    }
3694
3695    @Override
3696    public void updatePermissionFlags(String name, String packageName, int flagMask,
3697            int flagValues, int userId) {
3698        if (!sUserManager.exists(userId)) {
3699            return;
3700        }
3701
3702        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3703
3704        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3705                "updatePermissionFlags");
3706
3707        // Only the system can change these flags and nothing else.
3708        if (getCallingUid() != Process.SYSTEM_UID) {
3709            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3710            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3711            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3712            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3713        }
3714
3715        synchronized (mPackages) {
3716            final PackageParser.Package pkg = mPackages.get(packageName);
3717            if (pkg == null) {
3718                throw new IllegalArgumentException("Unknown package: " + packageName);
3719            }
3720
3721            final BasePermission bp = mSettings.mPermissions.get(name);
3722            if (bp == null) {
3723                throw new IllegalArgumentException("Unknown permission: " + name);
3724            }
3725
3726            SettingBase sb = (SettingBase) pkg.mExtras;
3727            if (sb == null) {
3728                throw new IllegalArgumentException("Unknown package: " + packageName);
3729            }
3730
3731            PermissionsState permissionsState = sb.getPermissionsState();
3732
3733            // Only the package manager can change flags for system component permissions.
3734            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3735            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3736                return;
3737            }
3738
3739            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3740
3741            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3742                // Install and runtime permissions are stored in different places,
3743                // so figure out what permission changed and persist the change.
3744                if (permissionsState.getInstallPermissionState(name) != null) {
3745                    scheduleWriteSettingsLocked();
3746                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3747                        || hadState) {
3748                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3749                }
3750            }
3751        }
3752    }
3753
3754    /**
3755     * Update the permission flags for all packages and runtime permissions of a user in order
3756     * to allow device or profile owner to remove POLICY_FIXED.
3757     */
3758    @Override
3759    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3760        if (!sUserManager.exists(userId)) {
3761            return;
3762        }
3763
3764        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3765
3766        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3767                "updatePermissionFlagsForAllApps");
3768
3769        // Only the system can change system fixed flags.
3770        if (getCallingUid() != Process.SYSTEM_UID) {
3771            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3772            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3773        }
3774
3775        synchronized (mPackages) {
3776            boolean changed = false;
3777            final int packageCount = mPackages.size();
3778            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3779                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3780                SettingBase sb = (SettingBase) pkg.mExtras;
3781                if (sb == null) {
3782                    continue;
3783                }
3784                PermissionsState permissionsState = sb.getPermissionsState();
3785                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3786                        userId, flagMask, flagValues);
3787            }
3788            if (changed) {
3789                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3790            }
3791        }
3792    }
3793
3794    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3795        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3796                != PackageManager.PERMISSION_GRANTED
3797            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3798                != PackageManager.PERMISSION_GRANTED) {
3799            throw new SecurityException(message + " requires "
3800                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3801                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3802        }
3803    }
3804
3805    @Override
3806    public boolean shouldShowRequestPermissionRationale(String permissionName,
3807            String packageName, int userId) {
3808        if (UserHandle.getCallingUserId() != userId) {
3809            mContext.enforceCallingPermission(
3810                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3811                    "canShowRequestPermissionRationale for user " + userId);
3812        }
3813
3814        final int uid = getPackageUid(packageName, userId);
3815        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3816            return false;
3817        }
3818
3819        if (checkPermission(permissionName, packageName, userId)
3820                == PackageManager.PERMISSION_GRANTED) {
3821            return false;
3822        }
3823
3824        final int flags;
3825
3826        final long identity = Binder.clearCallingIdentity();
3827        try {
3828            flags = getPermissionFlags(permissionName,
3829                    packageName, userId);
3830        } finally {
3831            Binder.restoreCallingIdentity(identity);
3832        }
3833
3834        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3835                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3836                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3837
3838        if ((flags & fixedFlags) != 0) {
3839            return false;
3840        }
3841
3842        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3843    }
3844
3845    @Override
3846    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3847        mContext.enforceCallingOrSelfPermission(
3848                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3849                "addOnPermissionsChangeListener");
3850
3851        synchronized (mPackages) {
3852            mOnPermissionChangeListeners.addListenerLocked(listener);
3853        }
3854    }
3855
3856    @Override
3857    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3858        synchronized (mPackages) {
3859            mOnPermissionChangeListeners.removeListenerLocked(listener);
3860        }
3861    }
3862
3863    @Override
3864    public boolean isProtectedBroadcast(String actionName) {
3865        synchronized (mPackages) {
3866            return mProtectedBroadcasts.contains(actionName);
3867        }
3868    }
3869
3870    @Override
3871    public int checkSignatures(String pkg1, String pkg2) {
3872        synchronized (mPackages) {
3873            final PackageParser.Package p1 = mPackages.get(pkg1);
3874            final PackageParser.Package p2 = mPackages.get(pkg2);
3875            if (p1 == null || p1.mExtras == null
3876                    || p2 == null || p2.mExtras == null) {
3877                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3878            }
3879            return compareSignatures(p1.mSignatures, p2.mSignatures);
3880        }
3881    }
3882
3883    @Override
3884    public int checkUidSignatures(int uid1, int uid2) {
3885        // Map to base uids.
3886        uid1 = UserHandle.getAppId(uid1);
3887        uid2 = UserHandle.getAppId(uid2);
3888        // reader
3889        synchronized (mPackages) {
3890            Signature[] s1;
3891            Signature[] s2;
3892            Object obj = mSettings.getUserIdLPr(uid1);
3893            if (obj != null) {
3894                if (obj instanceof SharedUserSetting) {
3895                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3896                } else if (obj instanceof PackageSetting) {
3897                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3898                } else {
3899                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900                }
3901            } else {
3902                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3903            }
3904            obj = mSettings.getUserIdLPr(uid2);
3905            if (obj != null) {
3906                if (obj instanceof SharedUserSetting) {
3907                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3908                } else if (obj instanceof PackageSetting) {
3909                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3910                } else {
3911                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3912                }
3913            } else {
3914                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3915            }
3916            return compareSignatures(s1, s2);
3917        }
3918    }
3919
3920    private void killUid(int appId, int userId, String reason) {
3921        final long identity = Binder.clearCallingIdentity();
3922        try {
3923            IActivityManager am = ActivityManagerNative.getDefault();
3924            if (am != null) {
3925                try {
3926                    am.killUid(appId, userId, reason);
3927                } catch (RemoteException e) {
3928                    /* ignore - same process */
3929                }
3930            }
3931        } finally {
3932            Binder.restoreCallingIdentity(identity);
3933        }
3934    }
3935
3936    /**
3937     * Compares two sets of signatures. Returns:
3938     * <br />
3939     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3940     * <br />
3941     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3942     * <br />
3943     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3944     * <br />
3945     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3946     * <br />
3947     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3948     */
3949    static int compareSignatures(Signature[] s1, Signature[] s2) {
3950        if (s1 == null) {
3951            return s2 == null
3952                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3953                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3954        }
3955
3956        if (s2 == null) {
3957            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3958        }
3959
3960        if (s1.length != s2.length) {
3961            return PackageManager.SIGNATURE_NO_MATCH;
3962        }
3963
3964        // Since both signature sets are of size 1, we can compare without HashSets.
3965        if (s1.length == 1) {
3966            return s1[0].equals(s2[0]) ?
3967                    PackageManager.SIGNATURE_MATCH :
3968                    PackageManager.SIGNATURE_NO_MATCH;
3969        }
3970
3971        ArraySet<Signature> set1 = new ArraySet<Signature>();
3972        for (Signature sig : s1) {
3973            set1.add(sig);
3974        }
3975        ArraySet<Signature> set2 = new ArraySet<Signature>();
3976        for (Signature sig : s2) {
3977            set2.add(sig);
3978        }
3979        // Make sure s2 contains all signatures in s1.
3980        if (set1.equals(set2)) {
3981            return PackageManager.SIGNATURE_MATCH;
3982        }
3983        return PackageManager.SIGNATURE_NO_MATCH;
3984    }
3985
3986    /**
3987     * If the database version for this type of package (internal storage or
3988     * external storage) is less than the version where package signatures
3989     * were updated, return true.
3990     */
3991    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3992        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3993        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3994    }
3995
3996    /**
3997     * Used for backward compatibility to make sure any packages with
3998     * certificate chains get upgraded to the new style. {@code existingSigs}
3999     * will be in the old format (since they were stored on disk from before the
4000     * system upgrade) and {@code scannedSigs} will be in the newer format.
4001     */
4002    private int compareSignaturesCompat(PackageSignatures existingSigs,
4003            PackageParser.Package scannedPkg) {
4004        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4005            return PackageManager.SIGNATURE_NO_MATCH;
4006        }
4007
4008        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4009        for (Signature sig : existingSigs.mSignatures) {
4010            existingSet.add(sig);
4011        }
4012        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4013        for (Signature sig : scannedPkg.mSignatures) {
4014            try {
4015                Signature[] chainSignatures = sig.getChainSignatures();
4016                for (Signature chainSig : chainSignatures) {
4017                    scannedCompatSet.add(chainSig);
4018                }
4019            } catch (CertificateEncodingException e) {
4020                scannedCompatSet.add(sig);
4021            }
4022        }
4023        /*
4024         * Make sure the expanded scanned set contains all signatures in the
4025         * existing one.
4026         */
4027        if (scannedCompatSet.equals(existingSet)) {
4028            // Migrate the old signatures to the new scheme.
4029            existingSigs.assignSignatures(scannedPkg.mSignatures);
4030            // The new KeySets will be re-added later in the scanning process.
4031            synchronized (mPackages) {
4032                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4033            }
4034            return PackageManager.SIGNATURE_MATCH;
4035        }
4036        return PackageManager.SIGNATURE_NO_MATCH;
4037    }
4038
4039    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4040        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4041        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4042    }
4043
4044    private int compareSignaturesRecover(PackageSignatures existingSigs,
4045            PackageParser.Package scannedPkg) {
4046        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4047            return PackageManager.SIGNATURE_NO_MATCH;
4048        }
4049
4050        String msg = null;
4051        try {
4052            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4053                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4054                        + scannedPkg.packageName);
4055                return PackageManager.SIGNATURE_MATCH;
4056            }
4057        } catch (CertificateException e) {
4058            msg = e.getMessage();
4059        }
4060
4061        logCriticalInfo(Log.INFO,
4062                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4063        return PackageManager.SIGNATURE_NO_MATCH;
4064    }
4065
4066    @Override
4067    public String[] getPackagesForUid(int uid) {
4068        uid = UserHandle.getAppId(uid);
4069        // reader
4070        synchronized (mPackages) {
4071            Object obj = mSettings.getUserIdLPr(uid);
4072            if (obj instanceof SharedUserSetting) {
4073                final SharedUserSetting sus = (SharedUserSetting) obj;
4074                final int N = sus.packages.size();
4075                final String[] res = new String[N];
4076                final Iterator<PackageSetting> it = sus.packages.iterator();
4077                int i = 0;
4078                while (it.hasNext()) {
4079                    res[i++] = it.next().name;
4080                }
4081                return res;
4082            } else if (obj instanceof PackageSetting) {
4083                final PackageSetting ps = (PackageSetting) obj;
4084                return new String[] { ps.name };
4085            }
4086        }
4087        return null;
4088    }
4089
4090    @Override
4091    public String getNameForUid(int uid) {
4092        // reader
4093        synchronized (mPackages) {
4094            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4095            if (obj instanceof SharedUserSetting) {
4096                final SharedUserSetting sus = (SharedUserSetting) obj;
4097                return sus.name + ":" + sus.userId;
4098            } else if (obj instanceof PackageSetting) {
4099                final PackageSetting ps = (PackageSetting) obj;
4100                return ps.name;
4101            }
4102        }
4103        return null;
4104    }
4105
4106    @Override
4107    public int getUidForSharedUser(String sharedUserName) {
4108        if(sharedUserName == null) {
4109            return -1;
4110        }
4111        // reader
4112        synchronized (mPackages) {
4113            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4114            if (suid == null) {
4115                return -1;
4116            }
4117            return suid.userId;
4118        }
4119    }
4120
4121    @Override
4122    public int getFlagsForUid(int uid) {
4123        synchronized (mPackages) {
4124            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4125            if (obj instanceof SharedUserSetting) {
4126                final SharedUserSetting sus = (SharedUserSetting) obj;
4127                return sus.pkgFlags;
4128            } else if (obj instanceof PackageSetting) {
4129                final PackageSetting ps = (PackageSetting) obj;
4130                return ps.pkgFlags;
4131            }
4132        }
4133        return 0;
4134    }
4135
4136    @Override
4137    public int getPrivateFlagsForUid(int uid) {
4138        synchronized (mPackages) {
4139            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4140            if (obj instanceof SharedUserSetting) {
4141                final SharedUserSetting sus = (SharedUserSetting) obj;
4142                return sus.pkgPrivateFlags;
4143            } else if (obj instanceof PackageSetting) {
4144                final PackageSetting ps = (PackageSetting) obj;
4145                return ps.pkgPrivateFlags;
4146            }
4147        }
4148        return 0;
4149    }
4150
4151    @Override
4152    public boolean isUidPrivileged(int uid) {
4153        uid = UserHandle.getAppId(uid);
4154        // reader
4155        synchronized (mPackages) {
4156            Object obj = mSettings.getUserIdLPr(uid);
4157            if (obj instanceof SharedUserSetting) {
4158                final SharedUserSetting sus = (SharedUserSetting) obj;
4159                final Iterator<PackageSetting> it = sus.packages.iterator();
4160                while (it.hasNext()) {
4161                    if (it.next().isPrivileged()) {
4162                        return true;
4163                    }
4164                }
4165            } else if (obj instanceof PackageSetting) {
4166                final PackageSetting ps = (PackageSetting) obj;
4167                return ps.isPrivileged();
4168            }
4169        }
4170        return false;
4171    }
4172
4173    @Override
4174    public String[] getAppOpPermissionPackages(String permissionName) {
4175        synchronized (mPackages) {
4176            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4177            if (pkgs == null) {
4178                return null;
4179            }
4180            return pkgs.toArray(new String[pkgs.size()]);
4181        }
4182    }
4183
4184    @Override
4185    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4186            int flags, int userId) {
4187        if (!sUserManager.exists(userId)) return null;
4188        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4189        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4190        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4191    }
4192
4193    @Override
4194    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4195            IntentFilter filter, int match, ComponentName activity) {
4196        final int userId = UserHandle.getCallingUserId();
4197        if (DEBUG_PREFERRED) {
4198            Log.v(TAG, "setLastChosenActivity intent=" + intent
4199                + " resolvedType=" + resolvedType
4200                + " flags=" + flags
4201                + " filter=" + filter
4202                + " match=" + match
4203                + " activity=" + activity);
4204            filter.dump(new PrintStreamPrinter(System.out), "    ");
4205        }
4206        intent.setComponent(null);
4207        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4208        // Find any earlier preferred or last chosen entries and nuke them
4209        findPreferredActivity(intent, resolvedType,
4210                flags, query, 0, false, true, false, userId);
4211        // Add the new activity as the last chosen for this filter
4212        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4213                "Setting last chosen");
4214    }
4215
4216    @Override
4217    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4218        final int userId = UserHandle.getCallingUserId();
4219        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4220        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4221        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4222                false, false, false, userId);
4223    }
4224
4225    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4226            int flags, List<ResolveInfo> query, int userId) {
4227        if (query != null) {
4228            final int N = query.size();
4229            if (N == 1) {
4230                return query.get(0);
4231            } else if (N > 1) {
4232                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4233                // If there is more than one activity with the same priority,
4234                // then let the user decide between them.
4235                ResolveInfo r0 = query.get(0);
4236                ResolveInfo r1 = query.get(1);
4237                if (DEBUG_INTENT_MATCHING || debug) {
4238                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4239                            + r1.activityInfo.name + "=" + r1.priority);
4240                }
4241                // If the first activity has a higher priority, or a different
4242                // default, then it is always desireable to pick it.
4243                if (r0.priority != r1.priority
4244                        || r0.preferredOrder != r1.preferredOrder
4245                        || r0.isDefault != r1.isDefault) {
4246                    return query.get(0);
4247                }
4248                // If we have saved a preference for a preferred activity for
4249                // this Intent, use that.
4250                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4251                        flags, query, r0.priority, true, false, debug, userId);
4252                if (ri != null) {
4253                    return ri;
4254                }
4255                ri = new ResolveInfo(mResolveInfo);
4256                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4257                ri.activityInfo.applicationInfo = new ApplicationInfo(
4258                        ri.activityInfo.applicationInfo);
4259                if (userId != 0) {
4260                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4261                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4262                }
4263                // Make sure that the resolver is displayable in car mode
4264                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4265                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4266                return ri;
4267            }
4268        }
4269        return null;
4270    }
4271
4272    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4273            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4274        final int N = query.size();
4275        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4276                .get(userId);
4277        // Get the list of persistent preferred activities that handle the intent
4278        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4279        List<PersistentPreferredActivity> pprefs = ppir != null
4280                ? ppir.queryIntent(intent, resolvedType,
4281                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4282                : null;
4283        if (pprefs != null && pprefs.size() > 0) {
4284            final int M = pprefs.size();
4285            for (int i=0; i<M; i++) {
4286                final PersistentPreferredActivity ppa = pprefs.get(i);
4287                if (DEBUG_PREFERRED || debug) {
4288                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4289                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4290                            + "\n  component=" + ppa.mComponent);
4291                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4292                }
4293                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4294                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4295                if (DEBUG_PREFERRED || debug) {
4296                    Slog.v(TAG, "Found persistent preferred activity:");
4297                    if (ai != null) {
4298                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4299                    } else {
4300                        Slog.v(TAG, "  null");
4301                    }
4302                }
4303                if (ai == null) {
4304                    // This previously registered persistent preferred activity
4305                    // component is no longer known. Ignore it and do NOT remove it.
4306                    continue;
4307                }
4308                for (int j=0; j<N; j++) {
4309                    final ResolveInfo ri = query.get(j);
4310                    if (!ri.activityInfo.applicationInfo.packageName
4311                            .equals(ai.applicationInfo.packageName)) {
4312                        continue;
4313                    }
4314                    if (!ri.activityInfo.name.equals(ai.name)) {
4315                        continue;
4316                    }
4317                    //  Found a persistent preference that can handle the intent.
4318                    if (DEBUG_PREFERRED || debug) {
4319                        Slog.v(TAG, "Returning persistent preferred activity: " +
4320                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4321                    }
4322                    return ri;
4323                }
4324            }
4325        }
4326        return null;
4327    }
4328
4329    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4330            List<ResolveInfo> query, int priority, boolean always,
4331            boolean removeMatches, boolean debug, int userId) {
4332        if (!sUserManager.exists(userId)) return null;
4333        // writer
4334        synchronized (mPackages) {
4335            if (intent.getSelector() != null) {
4336                intent = intent.getSelector();
4337            }
4338            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4339
4340            // Try to find a matching persistent preferred activity.
4341            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4342                    debug, userId);
4343
4344            // If a persistent preferred activity matched, use it.
4345            if (pri != null) {
4346                return pri;
4347            }
4348
4349            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4350            // Get the list of preferred activities that handle the intent
4351            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4352            List<PreferredActivity> prefs = pir != null
4353                    ? pir.queryIntent(intent, resolvedType,
4354                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4355                    : null;
4356            if (prefs != null && prefs.size() > 0) {
4357                boolean changed = false;
4358                try {
4359                    // First figure out how good the original match set is.
4360                    // We will only allow preferred activities that came
4361                    // from the same match quality.
4362                    int match = 0;
4363
4364                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4365
4366                    final int N = query.size();
4367                    for (int j=0; j<N; j++) {
4368                        final ResolveInfo ri = query.get(j);
4369                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4370                                + ": 0x" + Integer.toHexString(match));
4371                        if (ri.match > match) {
4372                            match = ri.match;
4373                        }
4374                    }
4375
4376                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4377                            + Integer.toHexString(match));
4378
4379                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4380                    final int M = prefs.size();
4381                    for (int i=0; i<M; i++) {
4382                        final PreferredActivity pa = prefs.get(i);
4383                        if (DEBUG_PREFERRED || debug) {
4384                            Slog.v(TAG, "Checking PreferredActivity ds="
4385                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4386                                    + "\n  component=" + pa.mPref.mComponent);
4387                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4388                        }
4389                        if (pa.mPref.mMatch != match) {
4390                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4391                                    + Integer.toHexString(pa.mPref.mMatch));
4392                            continue;
4393                        }
4394                        // If it's not an "always" type preferred activity and that's what we're
4395                        // looking for, skip it.
4396                        if (always && !pa.mPref.mAlways) {
4397                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4398                            continue;
4399                        }
4400                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4401                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4402                        if (DEBUG_PREFERRED || debug) {
4403                            Slog.v(TAG, "Found preferred activity:");
4404                            if (ai != null) {
4405                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4406                            } else {
4407                                Slog.v(TAG, "  null");
4408                            }
4409                        }
4410                        if (ai == null) {
4411                            // This previously registered preferred activity
4412                            // component is no longer known.  Most likely an update
4413                            // to the app was installed and in the new version this
4414                            // component no longer exists.  Clean it up by removing
4415                            // it from the preferred activities list, and skip it.
4416                            Slog.w(TAG, "Removing dangling preferred activity: "
4417                                    + pa.mPref.mComponent);
4418                            pir.removeFilter(pa);
4419                            changed = true;
4420                            continue;
4421                        }
4422                        for (int j=0; j<N; j++) {
4423                            final ResolveInfo ri = query.get(j);
4424                            if (!ri.activityInfo.applicationInfo.packageName
4425                                    .equals(ai.applicationInfo.packageName)) {
4426                                continue;
4427                            }
4428                            if (!ri.activityInfo.name.equals(ai.name)) {
4429                                continue;
4430                            }
4431
4432                            if (removeMatches) {
4433                                pir.removeFilter(pa);
4434                                changed = true;
4435                                if (DEBUG_PREFERRED) {
4436                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4437                                }
4438                                break;
4439                            }
4440
4441                            // Okay we found a previously set preferred or last chosen app.
4442                            // If the result set is different from when this
4443                            // was created, we need to clear it and re-ask the
4444                            // user their preference, if we're looking for an "always" type entry.
4445                            if (always && !pa.mPref.sameSet(query)) {
4446                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4447                                        + intent + " type " + resolvedType);
4448                                if (DEBUG_PREFERRED) {
4449                                    Slog.v(TAG, "Removing preferred activity since set changed "
4450                                            + pa.mPref.mComponent);
4451                                }
4452                                pir.removeFilter(pa);
4453                                // Re-add the filter as a "last chosen" entry (!always)
4454                                PreferredActivity lastChosen = new PreferredActivity(
4455                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4456                                pir.addFilter(lastChosen);
4457                                changed = true;
4458                                return null;
4459                            }
4460
4461                            // Yay! Either the set matched or we're looking for the last chosen
4462                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4463                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4464                            return ri;
4465                        }
4466                    }
4467                } finally {
4468                    if (changed) {
4469                        if (DEBUG_PREFERRED) {
4470                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4471                        }
4472                        scheduleWritePackageRestrictionsLocked(userId);
4473                    }
4474                }
4475            }
4476        }
4477        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4478        return null;
4479    }
4480
4481    /*
4482     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4483     */
4484    @Override
4485    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4486            int targetUserId) {
4487        mContext.enforceCallingOrSelfPermission(
4488                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4489        List<CrossProfileIntentFilter> matches =
4490                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4491        if (matches != null) {
4492            int size = matches.size();
4493            for (int i = 0; i < size; i++) {
4494                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4495            }
4496        }
4497        if (hasWebURI(intent)) {
4498            // cross-profile app linking works only towards the parent.
4499            final UserInfo parent = getProfileParent(sourceUserId);
4500            synchronized(mPackages) {
4501                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4502                        intent, resolvedType, 0, sourceUserId, parent.id);
4503                return xpDomainInfo != null;
4504            }
4505        }
4506        return false;
4507    }
4508
4509    private UserInfo getProfileParent(int userId) {
4510        final long identity = Binder.clearCallingIdentity();
4511        try {
4512            return sUserManager.getProfileParent(userId);
4513        } finally {
4514            Binder.restoreCallingIdentity(identity);
4515        }
4516    }
4517
4518    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4519            String resolvedType, int userId) {
4520        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4521        if (resolver != null) {
4522            return resolver.queryIntent(intent, resolvedType, false, userId);
4523        }
4524        return null;
4525    }
4526
4527    @Override
4528    public List<ResolveInfo> queryIntentActivities(Intent intent,
4529            String resolvedType, int flags, int userId) {
4530        if (!sUserManager.exists(userId)) return Collections.emptyList();
4531        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4532        ComponentName comp = intent.getComponent();
4533        if (comp == null) {
4534            if (intent.getSelector() != null) {
4535                intent = intent.getSelector();
4536                comp = intent.getComponent();
4537            }
4538        }
4539
4540        if (comp != null) {
4541            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4542            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4543            if (ai != null) {
4544                final ResolveInfo ri = new ResolveInfo();
4545                ri.activityInfo = ai;
4546                list.add(ri);
4547            }
4548            return list;
4549        }
4550
4551        // reader
4552        synchronized (mPackages) {
4553            final String pkgName = intent.getPackage();
4554            if (pkgName == null) {
4555                List<CrossProfileIntentFilter> matchingFilters =
4556                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4557                // Check for results that need to skip the current profile.
4558                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4559                        resolvedType, flags, userId);
4560                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4561                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4562                    result.add(xpResolveInfo);
4563                    return filterIfNotPrimaryUser(result, userId);
4564                }
4565
4566                // Check for results in the current profile.
4567                List<ResolveInfo> result = mActivities.queryIntent(
4568                        intent, resolvedType, flags, userId);
4569
4570                // Check for cross profile results.
4571                xpResolveInfo = queryCrossProfileIntents(
4572                        matchingFilters, intent, resolvedType, flags, userId);
4573                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4574                    result.add(xpResolveInfo);
4575                    Collections.sort(result, mResolvePrioritySorter);
4576                }
4577                result = filterIfNotPrimaryUser(result, userId);
4578                if (hasWebURI(intent)) {
4579                    CrossProfileDomainInfo xpDomainInfo = null;
4580                    final UserInfo parent = getProfileParent(userId);
4581                    if (parent != null) {
4582                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4583                                flags, userId, parent.id);
4584                    }
4585                    if (xpDomainInfo != null) {
4586                        if (xpResolveInfo != null) {
4587                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4588                            // in the result.
4589                            result.remove(xpResolveInfo);
4590                        }
4591                        if (result.size() == 0) {
4592                            result.add(xpDomainInfo.resolveInfo);
4593                            return result;
4594                        }
4595                    } else if (result.size() <= 1) {
4596                        return result;
4597                    }
4598                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4599                            xpDomainInfo, userId);
4600                    Collections.sort(result, mResolvePrioritySorter);
4601                }
4602                return result;
4603            }
4604            final PackageParser.Package pkg = mPackages.get(pkgName);
4605            if (pkg != null) {
4606                return filterIfNotPrimaryUser(
4607                        mActivities.queryIntentForPackage(
4608                                intent, resolvedType, flags, pkg.activities, userId),
4609                        userId);
4610            }
4611            return new ArrayList<ResolveInfo>();
4612        }
4613    }
4614
4615    private static class CrossProfileDomainInfo {
4616        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4617        ResolveInfo resolveInfo;
4618        /* Best domain verification status of the activities found in the other profile */
4619        int bestDomainVerificationStatus;
4620    }
4621
4622    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4623            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4624        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4625                sourceUserId)) {
4626            return null;
4627        }
4628        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4629                resolvedType, flags, parentUserId);
4630
4631        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4632            return null;
4633        }
4634        CrossProfileDomainInfo result = null;
4635        int size = resultTargetUser.size();
4636        for (int i = 0; i < size; i++) {
4637            ResolveInfo riTargetUser = resultTargetUser.get(i);
4638            // Intent filter verification is only for filters that specify a host. So don't return
4639            // those that handle all web uris.
4640            if (riTargetUser.handleAllWebDataURI) {
4641                continue;
4642            }
4643            String packageName = riTargetUser.activityInfo.packageName;
4644            PackageSetting ps = mSettings.mPackages.get(packageName);
4645            if (ps == null) {
4646                continue;
4647            }
4648            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4649            int status = (int)(verificationState >> 32);
4650            if (result == null) {
4651                result = new CrossProfileDomainInfo();
4652                result.resolveInfo =
4653                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4654                result.bestDomainVerificationStatus = status;
4655            } else {
4656                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4657                        result.bestDomainVerificationStatus);
4658            }
4659        }
4660        // Don't consider matches with status NEVER across profiles.
4661        if (result != null && result.bestDomainVerificationStatus
4662                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4663            return null;
4664        }
4665        return result;
4666    }
4667
4668    /**
4669     * Verification statuses are ordered from the worse to the best, except for
4670     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4671     */
4672    private int bestDomainVerificationStatus(int status1, int status2) {
4673        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4674            return status2;
4675        }
4676        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4677            return status1;
4678        }
4679        return (int) MathUtils.max(status1, status2);
4680    }
4681
4682    private boolean isUserEnabled(int userId) {
4683        long callingId = Binder.clearCallingIdentity();
4684        try {
4685            UserInfo userInfo = sUserManager.getUserInfo(userId);
4686            return userInfo != null && userInfo.isEnabled();
4687        } finally {
4688            Binder.restoreCallingIdentity(callingId);
4689        }
4690    }
4691
4692    /**
4693     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4694     *
4695     * @return filtered list
4696     */
4697    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4698        if (userId == UserHandle.USER_OWNER) {
4699            return resolveInfos;
4700        }
4701        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4702            ResolveInfo info = resolveInfos.get(i);
4703            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4704                resolveInfos.remove(i);
4705            }
4706        }
4707        return resolveInfos;
4708    }
4709
4710    private static boolean hasWebURI(Intent intent) {
4711        if (intent.getData() == null) {
4712            return false;
4713        }
4714        final String scheme = intent.getScheme();
4715        if (TextUtils.isEmpty(scheme)) {
4716            return false;
4717        }
4718        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4719    }
4720
4721    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4722            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4723            int userId) {
4724        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4725
4726        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4727            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4728                    candidates.size());
4729        }
4730
4731        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4732        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4733        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4734        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4735        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4736        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4737
4738        synchronized (mPackages) {
4739            final int count = candidates.size();
4740            // First, try to use linked apps. Partition the candidates into four lists:
4741            // one for the final results, one for the "do not use ever", one for "undefined status"
4742            // and finally one for "browser app type".
4743            for (int n=0; n<count; n++) {
4744                ResolveInfo info = candidates.get(n);
4745                String packageName = info.activityInfo.packageName;
4746                PackageSetting ps = mSettings.mPackages.get(packageName);
4747                if (ps != null) {
4748                    // Add to the special match all list (Browser use case)
4749                    if (info.handleAllWebDataURI) {
4750                        matchAllList.add(info);
4751                        continue;
4752                    }
4753                    // Try to get the status from User settings first
4754                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4755                    int status = (int)(packedStatus >> 32);
4756                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4757                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4758                        if (DEBUG_DOMAIN_VERIFICATION) {
4759                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4760                                    + " : linkgen=" + linkGeneration);
4761                        }
4762                        // Use link-enabled generation as preferredOrder, i.e.
4763                        // prefer newly-enabled over earlier-enabled.
4764                        info.preferredOrder = linkGeneration;
4765                        alwaysList.add(info);
4766                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4767                        if (DEBUG_DOMAIN_VERIFICATION) {
4768                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4769                        }
4770                        neverList.add(info);
4771                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4772                        if (DEBUG_DOMAIN_VERIFICATION) {
4773                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4774                        }
4775                        alwaysAskList.add(info);
4776                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4777                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4778                        if (DEBUG_DOMAIN_VERIFICATION) {
4779                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4780                        }
4781                        undefinedList.add(info);
4782                    }
4783                }
4784            }
4785
4786            // We'll want to include browser possibilities in a few cases
4787            boolean includeBrowser = false;
4788
4789            // First try to add the "always" resolution(s) for the current user, if any
4790            if (alwaysList.size() > 0) {
4791                result.addAll(alwaysList);
4792            } else {
4793                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4794                result.addAll(undefinedList);
4795                // Maybe add one for the other profile.
4796                if (xpDomainInfo != null && (
4797                        xpDomainInfo.bestDomainVerificationStatus
4798                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4799                    result.add(xpDomainInfo.resolveInfo);
4800                }
4801                includeBrowser = true;
4802            }
4803
4804            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4805            // If there were 'always' entries their preferred order has been set, so we also
4806            // back that off to make the alternatives equivalent
4807            if (alwaysAskList.size() > 0) {
4808                for (ResolveInfo i : result) {
4809                    i.preferredOrder = 0;
4810                }
4811                result.addAll(alwaysAskList);
4812                includeBrowser = true;
4813            }
4814
4815            if (includeBrowser) {
4816                // Also add browsers (all of them or only the default one)
4817                if (DEBUG_DOMAIN_VERIFICATION) {
4818                    Slog.v(TAG, "   ...including browsers in candidate set");
4819                }
4820                if ((matchFlags & MATCH_ALL) != 0) {
4821                    result.addAll(matchAllList);
4822                } else {
4823                    // Browser/generic handling case.  If there's a default browser, go straight
4824                    // to that (but only if there is no other higher-priority match).
4825                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4826                    int maxMatchPrio = 0;
4827                    ResolveInfo defaultBrowserMatch = null;
4828                    final int numCandidates = matchAllList.size();
4829                    for (int n = 0; n < numCandidates; n++) {
4830                        ResolveInfo info = matchAllList.get(n);
4831                        // track the highest overall match priority...
4832                        if (info.priority > maxMatchPrio) {
4833                            maxMatchPrio = info.priority;
4834                        }
4835                        // ...and the highest-priority default browser match
4836                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4837                            if (defaultBrowserMatch == null
4838                                    || (defaultBrowserMatch.priority < info.priority)) {
4839                                if (debug) {
4840                                    Slog.v(TAG, "Considering default browser match " + info);
4841                                }
4842                                defaultBrowserMatch = info;
4843                            }
4844                        }
4845                    }
4846                    if (defaultBrowserMatch != null
4847                            && defaultBrowserMatch.priority >= maxMatchPrio
4848                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4849                    {
4850                        if (debug) {
4851                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4852                        }
4853                        result.add(defaultBrowserMatch);
4854                    } else {
4855                        result.addAll(matchAllList);
4856                    }
4857                }
4858
4859                // If there is nothing selected, add all candidates and remove the ones that the user
4860                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4861                if (result.size() == 0) {
4862                    result.addAll(candidates);
4863                    result.removeAll(neverList);
4864                }
4865            }
4866        }
4867        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4868            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4869                    result.size());
4870            for (ResolveInfo info : result) {
4871                Slog.v(TAG, "  + " + info.activityInfo);
4872            }
4873        }
4874        return result;
4875    }
4876
4877    // Returns a packed value as a long:
4878    //
4879    // high 'int'-sized word: link status: undefined/ask/never/always.
4880    // low 'int'-sized word: relative priority among 'always' results.
4881    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4882        long result = ps.getDomainVerificationStatusForUser(userId);
4883        // if none available, get the master status
4884        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4885            if (ps.getIntentFilterVerificationInfo() != null) {
4886                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4887            }
4888        }
4889        return result;
4890    }
4891
4892    private ResolveInfo querySkipCurrentProfileIntents(
4893            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4894            int flags, int sourceUserId) {
4895        if (matchingFilters != null) {
4896            int size = matchingFilters.size();
4897            for (int i = 0; i < size; i ++) {
4898                CrossProfileIntentFilter filter = matchingFilters.get(i);
4899                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4900                    // Checking if there are activities in the target user that can handle the
4901                    // intent.
4902                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4903                            flags, sourceUserId);
4904                    if (resolveInfo != null) {
4905                        return resolveInfo;
4906                    }
4907                }
4908            }
4909        }
4910        return null;
4911    }
4912
4913    // Return matching ResolveInfo if any for skip current profile intent filters.
4914    private ResolveInfo queryCrossProfileIntents(
4915            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4916            int flags, int sourceUserId) {
4917        if (matchingFilters != null) {
4918            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4919            // match the same intent. For performance reasons, it is better not to
4920            // run queryIntent twice for the same userId
4921            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4922            int size = matchingFilters.size();
4923            for (int i = 0; i < size; i++) {
4924                CrossProfileIntentFilter filter = matchingFilters.get(i);
4925                int targetUserId = filter.getTargetUserId();
4926                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4927                        && !alreadyTriedUserIds.get(targetUserId)) {
4928                    // Checking if there are activities in the target user that can handle the
4929                    // intent.
4930                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4931                            flags, sourceUserId);
4932                    if (resolveInfo != null) return resolveInfo;
4933                    alreadyTriedUserIds.put(targetUserId, true);
4934                }
4935            }
4936        }
4937        return null;
4938    }
4939
4940    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4941            String resolvedType, int flags, int sourceUserId) {
4942        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4943                resolvedType, flags, filter.getTargetUserId());
4944        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4945            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4946        }
4947        return null;
4948    }
4949
4950    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4951            int sourceUserId, int targetUserId) {
4952        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4953        String className;
4954        if (targetUserId == UserHandle.USER_OWNER) {
4955            className = FORWARD_INTENT_TO_USER_OWNER;
4956        } else {
4957            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4958        }
4959        ComponentName forwardingActivityComponentName = new ComponentName(
4960                mAndroidApplication.packageName, className);
4961        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4962                sourceUserId);
4963        if (targetUserId == UserHandle.USER_OWNER) {
4964            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4965            forwardingResolveInfo.noResourceId = true;
4966        }
4967        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4968        forwardingResolveInfo.priority = 0;
4969        forwardingResolveInfo.preferredOrder = 0;
4970        forwardingResolveInfo.match = 0;
4971        forwardingResolveInfo.isDefault = true;
4972        forwardingResolveInfo.filter = filter;
4973        forwardingResolveInfo.targetUserId = targetUserId;
4974        return forwardingResolveInfo;
4975    }
4976
4977    @Override
4978    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4979            Intent[] specifics, String[] specificTypes, Intent intent,
4980            String resolvedType, int flags, int userId) {
4981        if (!sUserManager.exists(userId)) return Collections.emptyList();
4982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4983                false, "query intent activity options");
4984        final String resultsAction = intent.getAction();
4985
4986        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4987                | PackageManager.GET_RESOLVED_FILTER, userId);
4988
4989        if (DEBUG_INTENT_MATCHING) {
4990            Log.v(TAG, "Query " + intent + ": " + results);
4991        }
4992
4993        int specificsPos = 0;
4994        int N;
4995
4996        // todo: note that the algorithm used here is O(N^2).  This
4997        // isn't a problem in our current environment, but if we start running
4998        // into situations where we have more than 5 or 10 matches then this
4999        // should probably be changed to something smarter...
5000
5001        // First we go through and resolve each of the specific items
5002        // that were supplied, taking care of removing any corresponding
5003        // duplicate items in the generic resolve list.
5004        if (specifics != null) {
5005            for (int i=0; i<specifics.length; i++) {
5006                final Intent sintent = specifics[i];
5007                if (sintent == null) {
5008                    continue;
5009                }
5010
5011                if (DEBUG_INTENT_MATCHING) {
5012                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5013                }
5014
5015                String action = sintent.getAction();
5016                if (resultsAction != null && resultsAction.equals(action)) {
5017                    // If this action was explicitly requested, then don't
5018                    // remove things that have it.
5019                    action = null;
5020                }
5021
5022                ResolveInfo ri = null;
5023                ActivityInfo ai = null;
5024
5025                ComponentName comp = sintent.getComponent();
5026                if (comp == null) {
5027                    ri = resolveIntent(
5028                        sintent,
5029                        specificTypes != null ? specificTypes[i] : null,
5030                            flags, userId);
5031                    if (ri == null) {
5032                        continue;
5033                    }
5034                    if (ri == mResolveInfo) {
5035                        // ACK!  Must do something better with this.
5036                    }
5037                    ai = ri.activityInfo;
5038                    comp = new ComponentName(ai.applicationInfo.packageName,
5039                            ai.name);
5040                } else {
5041                    ai = getActivityInfo(comp, flags, userId);
5042                    if (ai == null) {
5043                        continue;
5044                    }
5045                }
5046
5047                // Look for any generic query activities that are duplicates
5048                // of this specific one, and remove them from the results.
5049                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5050                N = results.size();
5051                int j;
5052                for (j=specificsPos; j<N; j++) {
5053                    ResolveInfo sri = results.get(j);
5054                    if ((sri.activityInfo.name.equals(comp.getClassName())
5055                            && sri.activityInfo.applicationInfo.packageName.equals(
5056                                    comp.getPackageName()))
5057                        || (action != null && sri.filter.matchAction(action))) {
5058                        results.remove(j);
5059                        if (DEBUG_INTENT_MATCHING) Log.v(
5060                            TAG, "Removing duplicate item from " + j
5061                            + " due to specific " + specificsPos);
5062                        if (ri == null) {
5063                            ri = sri;
5064                        }
5065                        j--;
5066                        N--;
5067                    }
5068                }
5069
5070                // Add this specific item to its proper place.
5071                if (ri == null) {
5072                    ri = new ResolveInfo();
5073                    ri.activityInfo = ai;
5074                }
5075                results.add(specificsPos, ri);
5076                ri.specificIndex = i;
5077                specificsPos++;
5078            }
5079        }
5080
5081        // Now we go through the remaining generic results and remove any
5082        // duplicate actions that are found here.
5083        N = results.size();
5084        for (int i=specificsPos; i<N-1; i++) {
5085            final ResolveInfo rii = results.get(i);
5086            if (rii.filter == null) {
5087                continue;
5088            }
5089
5090            // Iterate over all of the actions of this result's intent
5091            // filter...  typically this should be just one.
5092            final Iterator<String> it = rii.filter.actionsIterator();
5093            if (it == null) {
5094                continue;
5095            }
5096            while (it.hasNext()) {
5097                final String action = it.next();
5098                if (resultsAction != null && resultsAction.equals(action)) {
5099                    // If this action was explicitly requested, then don't
5100                    // remove things that have it.
5101                    continue;
5102                }
5103                for (int j=i+1; j<N; j++) {
5104                    final ResolveInfo rij = results.get(j);
5105                    if (rij.filter != null && rij.filter.hasAction(action)) {
5106                        results.remove(j);
5107                        if (DEBUG_INTENT_MATCHING) Log.v(
5108                            TAG, "Removing duplicate item from " + j
5109                            + " due to action " + action + " at " + i);
5110                        j--;
5111                        N--;
5112                    }
5113                }
5114            }
5115
5116            // If the caller didn't request filter information, drop it now
5117            // so we don't have to marshall/unmarshall it.
5118            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5119                rii.filter = null;
5120            }
5121        }
5122
5123        // Filter out the caller activity if so requested.
5124        if (caller != null) {
5125            N = results.size();
5126            for (int i=0; i<N; i++) {
5127                ActivityInfo ainfo = results.get(i).activityInfo;
5128                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5129                        && caller.getClassName().equals(ainfo.name)) {
5130                    results.remove(i);
5131                    break;
5132                }
5133            }
5134        }
5135
5136        // If the caller didn't request filter information,
5137        // drop them now so we don't have to
5138        // marshall/unmarshall it.
5139        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5140            N = results.size();
5141            for (int i=0; i<N; i++) {
5142                results.get(i).filter = null;
5143            }
5144        }
5145
5146        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5147        return results;
5148    }
5149
5150    @Override
5151    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5152            int userId) {
5153        if (!sUserManager.exists(userId)) return Collections.emptyList();
5154        ComponentName comp = intent.getComponent();
5155        if (comp == null) {
5156            if (intent.getSelector() != null) {
5157                intent = intent.getSelector();
5158                comp = intent.getComponent();
5159            }
5160        }
5161        if (comp != null) {
5162            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5163            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5164            if (ai != null) {
5165                ResolveInfo ri = new ResolveInfo();
5166                ri.activityInfo = ai;
5167                list.add(ri);
5168            }
5169            return list;
5170        }
5171
5172        // reader
5173        synchronized (mPackages) {
5174            String pkgName = intent.getPackage();
5175            if (pkgName == null) {
5176                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5177            }
5178            final PackageParser.Package pkg = mPackages.get(pkgName);
5179            if (pkg != null) {
5180                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5181                        userId);
5182            }
5183            return null;
5184        }
5185    }
5186
5187    @Override
5188    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5189        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5190        if (!sUserManager.exists(userId)) return null;
5191        if (query != null) {
5192            if (query.size() >= 1) {
5193                // If there is more than one service with the same priority,
5194                // just arbitrarily pick the first one.
5195                return query.get(0);
5196            }
5197        }
5198        return null;
5199    }
5200
5201    @Override
5202    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5203            int userId) {
5204        if (!sUserManager.exists(userId)) return Collections.emptyList();
5205        ComponentName comp = intent.getComponent();
5206        if (comp == null) {
5207            if (intent.getSelector() != null) {
5208                intent = intent.getSelector();
5209                comp = intent.getComponent();
5210            }
5211        }
5212        if (comp != null) {
5213            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5214            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5215            if (si != null) {
5216                final ResolveInfo ri = new ResolveInfo();
5217                ri.serviceInfo = si;
5218                list.add(ri);
5219            }
5220            return list;
5221        }
5222
5223        // reader
5224        synchronized (mPackages) {
5225            String pkgName = intent.getPackage();
5226            if (pkgName == null) {
5227                return mServices.queryIntent(intent, resolvedType, flags, userId);
5228            }
5229            final PackageParser.Package pkg = mPackages.get(pkgName);
5230            if (pkg != null) {
5231                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5232                        userId);
5233            }
5234            return null;
5235        }
5236    }
5237
5238    @Override
5239    public List<ResolveInfo> queryIntentContentProviders(
5240            Intent intent, String resolvedType, int flags, int userId) {
5241        if (!sUserManager.exists(userId)) return Collections.emptyList();
5242        ComponentName comp = intent.getComponent();
5243        if (comp == null) {
5244            if (intent.getSelector() != null) {
5245                intent = intent.getSelector();
5246                comp = intent.getComponent();
5247            }
5248        }
5249        if (comp != null) {
5250            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5251            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5252            if (pi != null) {
5253                final ResolveInfo ri = new ResolveInfo();
5254                ri.providerInfo = pi;
5255                list.add(ri);
5256            }
5257            return list;
5258        }
5259
5260        // reader
5261        synchronized (mPackages) {
5262            String pkgName = intent.getPackage();
5263            if (pkgName == null) {
5264                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5265            }
5266            final PackageParser.Package pkg = mPackages.get(pkgName);
5267            if (pkg != null) {
5268                return mProviders.queryIntentForPackage(
5269                        intent, resolvedType, flags, pkg.providers, userId);
5270            }
5271            return null;
5272        }
5273    }
5274
5275    @Override
5276    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5277        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5278
5279        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5280
5281        // writer
5282        synchronized (mPackages) {
5283            ArrayList<PackageInfo> list;
5284            if (listUninstalled) {
5285                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5286                for (PackageSetting ps : mSettings.mPackages.values()) {
5287                    PackageInfo pi;
5288                    if (ps.pkg != null) {
5289                        pi = generatePackageInfo(ps.pkg, flags, userId);
5290                    } else {
5291                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5292                    }
5293                    if (pi != null) {
5294                        list.add(pi);
5295                    }
5296                }
5297            } else {
5298                list = new ArrayList<PackageInfo>(mPackages.size());
5299                for (PackageParser.Package p : mPackages.values()) {
5300                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5301                    if (pi != null) {
5302                        list.add(pi);
5303                    }
5304                }
5305            }
5306
5307            return new ParceledListSlice<PackageInfo>(list);
5308        }
5309    }
5310
5311    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5312            String[] permissions, boolean[] tmp, int flags, int userId) {
5313        int numMatch = 0;
5314        final PermissionsState permissionsState = ps.getPermissionsState();
5315        for (int i=0; i<permissions.length; i++) {
5316            final String permission = permissions[i];
5317            if (permissionsState.hasPermission(permission, userId)) {
5318                tmp[i] = true;
5319                numMatch++;
5320            } else {
5321                tmp[i] = false;
5322            }
5323        }
5324        if (numMatch == 0) {
5325            return;
5326        }
5327        PackageInfo pi;
5328        if (ps.pkg != null) {
5329            pi = generatePackageInfo(ps.pkg, flags, userId);
5330        } else {
5331            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5332        }
5333        // The above might return null in cases of uninstalled apps or install-state
5334        // skew across users/profiles.
5335        if (pi != null) {
5336            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5337                if (numMatch == permissions.length) {
5338                    pi.requestedPermissions = permissions;
5339                } else {
5340                    pi.requestedPermissions = new String[numMatch];
5341                    numMatch = 0;
5342                    for (int i=0; i<permissions.length; i++) {
5343                        if (tmp[i]) {
5344                            pi.requestedPermissions[numMatch] = permissions[i];
5345                            numMatch++;
5346                        }
5347                    }
5348                }
5349            }
5350            list.add(pi);
5351        }
5352    }
5353
5354    @Override
5355    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5356            String[] permissions, int flags, int userId) {
5357        if (!sUserManager.exists(userId)) return null;
5358        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5359
5360        // writer
5361        synchronized (mPackages) {
5362            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5363            boolean[] tmpBools = new boolean[permissions.length];
5364            if (listUninstalled) {
5365                for (PackageSetting ps : mSettings.mPackages.values()) {
5366                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5367                }
5368            } else {
5369                for (PackageParser.Package pkg : mPackages.values()) {
5370                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5371                    if (ps != null) {
5372                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5373                                userId);
5374                    }
5375                }
5376            }
5377
5378            return new ParceledListSlice<PackageInfo>(list);
5379        }
5380    }
5381
5382    @Override
5383    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5384        if (!sUserManager.exists(userId)) return null;
5385        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5386
5387        // writer
5388        synchronized (mPackages) {
5389            ArrayList<ApplicationInfo> list;
5390            if (listUninstalled) {
5391                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5392                for (PackageSetting ps : mSettings.mPackages.values()) {
5393                    ApplicationInfo ai;
5394                    if (ps.pkg != null) {
5395                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5396                                ps.readUserState(userId), userId);
5397                    } else {
5398                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5399                    }
5400                    if (ai != null) {
5401                        list.add(ai);
5402                    }
5403                }
5404            } else {
5405                list = new ArrayList<ApplicationInfo>(mPackages.size());
5406                for (PackageParser.Package p : mPackages.values()) {
5407                    if (p.mExtras != null) {
5408                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5409                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5410                        if (ai != null) {
5411                            list.add(ai);
5412                        }
5413                    }
5414                }
5415            }
5416
5417            return new ParceledListSlice<ApplicationInfo>(list);
5418        }
5419    }
5420
5421    public List<ApplicationInfo> getPersistentApplications(int flags) {
5422        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5423
5424        // reader
5425        synchronized (mPackages) {
5426            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5427            final int userId = UserHandle.getCallingUserId();
5428            while (i.hasNext()) {
5429                final PackageParser.Package p = i.next();
5430                if (p.applicationInfo != null
5431                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5432                        && (!mSafeMode || isSystemApp(p))) {
5433                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5434                    if (ps != null) {
5435                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5436                                ps.readUserState(userId), userId);
5437                        if (ai != null) {
5438                            finalList.add(ai);
5439                        }
5440                    }
5441                }
5442            }
5443        }
5444
5445        return finalList;
5446    }
5447
5448    @Override
5449    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5450        if (!sUserManager.exists(userId)) return null;
5451        // reader
5452        synchronized (mPackages) {
5453            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5454            PackageSetting ps = provider != null
5455                    ? mSettings.mPackages.get(provider.owner.packageName)
5456                    : null;
5457            return ps != null
5458                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5459                    && (!mSafeMode || (provider.info.applicationInfo.flags
5460                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5461                    ? PackageParser.generateProviderInfo(provider, flags,
5462                            ps.readUserState(userId), userId)
5463                    : null;
5464        }
5465    }
5466
5467    /**
5468     * @deprecated
5469     */
5470    @Deprecated
5471    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5472        // reader
5473        synchronized (mPackages) {
5474            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5475                    .entrySet().iterator();
5476            final int userId = UserHandle.getCallingUserId();
5477            while (i.hasNext()) {
5478                Map.Entry<String, PackageParser.Provider> entry = i.next();
5479                PackageParser.Provider p = entry.getValue();
5480                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5481
5482                if (ps != null && p.syncable
5483                        && (!mSafeMode || (p.info.applicationInfo.flags
5484                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5485                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5486                            ps.readUserState(userId), userId);
5487                    if (info != null) {
5488                        outNames.add(entry.getKey());
5489                        outInfo.add(info);
5490                    }
5491                }
5492            }
5493        }
5494    }
5495
5496    @Override
5497    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5498            int uid, int flags) {
5499        ArrayList<ProviderInfo> finalList = null;
5500        // reader
5501        synchronized (mPackages) {
5502            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5503            final int userId = processName != null ?
5504                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5505            while (i.hasNext()) {
5506                final PackageParser.Provider p = i.next();
5507                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5508                if (ps != null && p.info.authority != null
5509                        && (processName == null
5510                                || (p.info.processName.equals(processName)
5511                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5512                        && mSettings.isEnabledLPr(p.info, flags, userId)
5513                        && (!mSafeMode
5514                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5515                    if (finalList == null) {
5516                        finalList = new ArrayList<ProviderInfo>(3);
5517                    }
5518                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5519                            ps.readUserState(userId), userId);
5520                    if (info != null) {
5521                        finalList.add(info);
5522                    }
5523                }
5524            }
5525        }
5526
5527        if (finalList != null) {
5528            Collections.sort(finalList, mProviderInitOrderSorter);
5529            return new ParceledListSlice<ProviderInfo>(finalList);
5530        }
5531
5532        return null;
5533    }
5534
5535    @Override
5536    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5537            int flags) {
5538        // reader
5539        synchronized (mPackages) {
5540            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5541            return PackageParser.generateInstrumentationInfo(i, flags);
5542        }
5543    }
5544
5545    @Override
5546    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5547            int flags) {
5548        ArrayList<InstrumentationInfo> finalList =
5549            new ArrayList<InstrumentationInfo>();
5550
5551        // reader
5552        synchronized (mPackages) {
5553            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5554            while (i.hasNext()) {
5555                final PackageParser.Instrumentation p = i.next();
5556                if (targetPackage == null
5557                        || targetPackage.equals(p.info.targetPackage)) {
5558                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5559                            flags);
5560                    if (ii != null) {
5561                        finalList.add(ii);
5562                    }
5563                }
5564            }
5565        }
5566
5567        return finalList;
5568    }
5569
5570    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5571        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5572        if (overlays == null) {
5573            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5574            return;
5575        }
5576        for (PackageParser.Package opkg : overlays.values()) {
5577            // Not much to do if idmap fails: we already logged the error
5578            // and we certainly don't want to abort installation of pkg simply
5579            // because an overlay didn't fit properly. For these reasons,
5580            // ignore the return value of createIdmapForPackagePairLI.
5581            createIdmapForPackagePairLI(pkg, opkg);
5582        }
5583    }
5584
5585    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5586            PackageParser.Package opkg) {
5587        if (!opkg.mTrustedOverlay) {
5588            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5589                    opkg.baseCodePath + ": overlay not trusted");
5590            return false;
5591        }
5592        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5593        if (overlaySet == null) {
5594            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5595                    opkg.baseCodePath + " but target package has no known overlays");
5596            return false;
5597        }
5598        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5599        // TODO: generate idmap for split APKs
5600        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5601            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5602                    + opkg.baseCodePath);
5603            return false;
5604        }
5605        PackageParser.Package[] overlayArray =
5606            overlaySet.values().toArray(new PackageParser.Package[0]);
5607        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5608            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5609                return p1.mOverlayPriority - p2.mOverlayPriority;
5610            }
5611        };
5612        Arrays.sort(overlayArray, cmp);
5613
5614        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5615        int i = 0;
5616        for (PackageParser.Package p : overlayArray) {
5617            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5618        }
5619        return true;
5620    }
5621
5622    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5623        final File[] files = dir.listFiles();
5624        if (ArrayUtils.isEmpty(files)) {
5625            Log.d(TAG, "No files in app dir " + dir);
5626            return;
5627        }
5628
5629        if (DEBUG_PACKAGE_SCANNING) {
5630            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5631                    + " flags=0x" + Integer.toHexString(parseFlags));
5632        }
5633
5634        for (File file : files) {
5635            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5636                    && !PackageInstallerService.isStageName(file.getName());
5637            if (!isPackage) {
5638                // Ignore entries which are not packages
5639                continue;
5640            }
5641            try {
5642                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5643                        scanFlags, currentTime, null);
5644            } catch (PackageManagerException e) {
5645                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5646
5647                // Delete invalid userdata apps
5648                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5649                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5650                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5651                    if (file.isDirectory()) {
5652                        mInstaller.rmPackageDir(file.getAbsolutePath());
5653                    } else {
5654                        file.delete();
5655                    }
5656                }
5657            }
5658        }
5659    }
5660
5661    private static File getSettingsProblemFile() {
5662        File dataDir = Environment.getDataDirectory();
5663        File systemDir = new File(dataDir, "system");
5664        File fname = new File(systemDir, "uiderrors.txt");
5665        return fname;
5666    }
5667
5668    static void reportSettingsProblem(int priority, String msg) {
5669        logCriticalInfo(priority, msg);
5670    }
5671
5672    static void logCriticalInfo(int priority, String msg) {
5673        Slog.println(priority, TAG, msg);
5674        EventLogTags.writePmCriticalInfo(msg);
5675        try {
5676            File fname = getSettingsProblemFile();
5677            FileOutputStream out = new FileOutputStream(fname, true);
5678            PrintWriter pw = new FastPrintWriter(out);
5679            SimpleDateFormat formatter = new SimpleDateFormat();
5680            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5681            pw.println(dateString + ": " + msg);
5682            pw.close();
5683            FileUtils.setPermissions(
5684                    fname.toString(),
5685                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5686                    -1, -1);
5687        } catch (java.io.IOException e) {
5688        }
5689    }
5690
5691    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5692            PackageParser.Package pkg, File srcFile, int parseFlags)
5693            throws PackageManagerException {
5694        if (ps != null
5695                && ps.codePath.equals(srcFile)
5696                && ps.timeStamp == srcFile.lastModified()
5697                && !isCompatSignatureUpdateNeeded(pkg)
5698                && !isRecoverSignatureUpdateNeeded(pkg)) {
5699            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5700            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5701            ArraySet<PublicKey> signingKs;
5702            synchronized (mPackages) {
5703                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5704            }
5705            if (ps.signatures.mSignatures != null
5706                    && ps.signatures.mSignatures.length != 0
5707                    && signingKs != null) {
5708                // Optimization: reuse the existing cached certificates
5709                // if the package appears to be unchanged.
5710                pkg.mSignatures = ps.signatures.mSignatures;
5711                pkg.mSigningKeys = signingKs;
5712                return;
5713            }
5714
5715            Slog.w(TAG, "PackageSetting for " + ps.name
5716                    + " is missing signatures.  Collecting certs again to recover them.");
5717        } else {
5718            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5719        }
5720
5721        try {
5722            pp.collectCertificates(pkg, parseFlags);
5723            pp.collectManifestDigest(pkg);
5724        } catch (PackageParserException e) {
5725            throw PackageManagerException.from(e);
5726        }
5727    }
5728
5729    /*
5730     *  Scan a package and return the newly parsed package.
5731     *  Returns null in case of errors and the error code is stored in mLastScanError
5732     */
5733    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5734            long currentTime, UserHandle user) throws PackageManagerException {
5735        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5736        parseFlags |= mDefParseFlags;
5737        PackageParser pp = new PackageParser();
5738        pp.setSeparateProcesses(mSeparateProcesses);
5739        pp.setOnlyCoreApps(mOnlyCore);
5740        pp.setDisplayMetrics(mMetrics);
5741
5742        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5743            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5744        }
5745
5746        final PackageParser.Package pkg;
5747        try {
5748            pkg = pp.parsePackage(scanFile, parseFlags);
5749        } catch (PackageParserException e) {
5750            throw PackageManagerException.from(e);
5751        }
5752
5753        PackageSetting ps = null;
5754        PackageSetting updatedPkg;
5755        // reader
5756        synchronized (mPackages) {
5757            // Look to see if we already know about this package.
5758            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5759            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5760                // This package has been renamed to its original name.  Let's
5761                // use that.
5762                ps = mSettings.peekPackageLPr(oldName);
5763            }
5764            // If there was no original package, see one for the real package name.
5765            if (ps == null) {
5766                ps = mSettings.peekPackageLPr(pkg.packageName);
5767            }
5768            // Check to see if this package could be hiding/updating a system
5769            // package.  Must look for it either under the original or real
5770            // package name depending on our state.
5771            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5772            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5773        }
5774        boolean updatedPkgBetter = false;
5775        // First check if this is a system package that may involve an update
5776        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5777            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5778            // it needs to drop FLAG_PRIVILEGED.
5779            if (locationIsPrivileged(scanFile)) {
5780                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5781            } else {
5782                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5783            }
5784
5785            if (ps != null && !ps.codePath.equals(scanFile)) {
5786                // The path has changed from what was last scanned...  check the
5787                // version of the new path against what we have stored to determine
5788                // what to do.
5789                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5790                if (pkg.mVersionCode <= ps.versionCode) {
5791                    // The system package has been updated and the code path does not match
5792                    // Ignore entry. Skip it.
5793                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5794                            + " ignored: updated version " + ps.versionCode
5795                            + " better than this " + pkg.mVersionCode);
5796                    if (!updatedPkg.codePath.equals(scanFile)) {
5797                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5798                                + ps.name + " changing from " + updatedPkg.codePathString
5799                                + " to " + scanFile);
5800                        updatedPkg.codePath = scanFile;
5801                        updatedPkg.codePathString = scanFile.toString();
5802                        updatedPkg.resourcePath = scanFile;
5803                        updatedPkg.resourcePathString = scanFile.toString();
5804                    }
5805                    updatedPkg.pkg = pkg;
5806                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5807                            "Package " + ps.name + " at " + scanFile
5808                                    + " ignored: updated version " + ps.versionCode
5809                                    + " better than this " + pkg.mVersionCode);
5810                } else {
5811                    // The current app on the system partition is better than
5812                    // what we have updated to on the data partition; switch
5813                    // back to the system partition version.
5814                    // At this point, its safely assumed that package installation for
5815                    // apps in system partition will go through. If not there won't be a working
5816                    // version of the app
5817                    // writer
5818                    synchronized (mPackages) {
5819                        // Just remove the loaded entries from package lists.
5820                        mPackages.remove(ps.name);
5821                    }
5822
5823                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5824                            + " reverting from " + ps.codePathString
5825                            + ": new version " + pkg.mVersionCode
5826                            + " better than installed " + ps.versionCode);
5827
5828                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5829                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5830                    synchronized (mInstallLock) {
5831                        args.cleanUpResourcesLI();
5832                    }
5833                    synchronized (mPackages) {
5834                        mSettings.enableSystemPackageLPw(ps.name);
5835                    }
5836                    updatedPkgBetter = true;
5837                }
5838            }
5839        }
5840
5841        if (updatedPkg != null) {
5842            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5843            // initially
5844            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5845
5846            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5847            // flag set initially
5848            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5849                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5850            }
5851        }
5852
5853        // Verify certificates against what was last scanned
5854        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5855
5856        /*
5857         * A new system app appeared, but we already had a non-system one of the
5858         * same name installed earlier.
5859         */
5860        boolean shouldHideSystemApp = false;
5861        if (updatedPkg == null && ps != null
5862                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5863            /*
5864             * Check to make sure the signatures match first. If they don't,
5865             * wipe the installed application and its data.
5866             */
5867            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5868                    != PackageManager.SIGNATURE_MATCH) {
5869                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5870                        + " signatures don't match existing userdata copy; removing");
5871                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5872                ps = null;
5873            } else {
5874                /*
5875                 * If the newly-added system app is an older version than the
5876                 * already installed version, hide it. It will be scanned later
5877                 * and re-added like an update.
5878                 */
5879                if (pkg.mVersionCode <= ps.versionCode) {
5880                    shouldHideSystemApp = true;
5881                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5882                            + " but new version " + pkg.mVersionCode + " better than installed "
5883                            + ps.versionCode + "; hiding system");
5884                } else {
5885                    /*
5886                     * The newly found system app is a newer version that the
5887                     * one previously installed. Simply remove the
5888                     * already-installed application and replace it with our own
5889                     * while keeping the application data.
5890                     */
5891                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5892                            + " reverting from " + ps.codePathString + ": new version "
5893                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5894                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5895                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5896                    synchronized (mInstallLock) {
5897                        args.cleanUpResourcesLI();
5898                    }
5899                }
5900            }
5901        }
5902
5903        // The apk is forward locked (not public) if its code and resources
5904        // are kept in different files. (except for app in either system or
5905        // vendor path).
5906        // TODO grab this value from PackageSettings
5907        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5908            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5909                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5910            }
5911        }
5912
5913        // TODO: extend to support forward-locked splits
5914        String resourcePath = null;
5915        String baseResourcePath = null;
5916        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5917            if (ps != null && ps.resourcePathString != null) {
5918                resourcePath = ps.resourcePathString;
5919                baseResourcePath = ps.resourcePathString;
5920            } else {
5921                // Should not happen at all. Just log an error.
5922                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5923            }
5924        } else {
5925            resourcePath = pkg.codePath;
5926            baseResourcePath = pkg.baseCodePath;
5927        }
5928
5929        // Set application objects path explicitly.
5930        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5931        pkg.applicationInfo.setCodePath(pkg.codePath);
5932        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5933        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5934        pkg.applicationInfo.setResourcePath(resourcePath);
5935        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5936        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5937
5938        // Note that we invoke the following method only if we are about to unpack an application
5939        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5940                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5941
5942        /*
5943         * If the system app should be overridden by a previously installed
5944         * data, hide the system app now and let the /data/app scan pick it up
5945         * again.
5946         */
5947        if (shouldHideSystemApp) {
5948            synchronized (mPackages) {
5949                mSettings.disableSystemPackageLPw(pkg.packageName);
5950            }
5951        }
5952
5953        return scannedPkg;
5954    }
5955
5956    private static String fixProcessName(String defProcessName,
5957            String processName, int uid) {
5958        if (processName == null) {
5959            return defProcessName;
5960        }
5961        return processName;
5962    }
5963
5964    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5965            throws PackageManagerException {
5966        if (pkgSetting.signatures.mSignatures != null) {
5967            // Already existing package. Make sure signatures match
5968            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5969                    == PackageManager.SIGNATURE_MATCH;
5970            if (!match) {
5971                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5972                        == PackageManager.SIGNATURE_MATCH;
5973            }
5974            if (!match) {
5975                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5976                        == PackageManager.SIGNATURE_MATCH;
5977            }
5978            if (!match) {
5979                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5980                        + pkg.packageName + " signatures do not match the "
5981                        + "previously installed version; ignoring!");
5982            }
5983        }
5984
5985        // Check for shared user signatures
5986        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5987            // Already existing package. Make sure signatures match
5988            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5989                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5990            if (!match) {
5991                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5992                        == PackageManager.SIGNATURE_MATCH;
5993            }
5994            if (!match) {
5995                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5996                        == PackageManager.SIGNATURE_MATCH;
5997            }
5998            if (!match) {
5999                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6000                        "Package " + pkg.packageName
6001                        + " has no signatures that match those in shared user "
6002                        + pkgSetting.sharedUser.name + "; ignoring!");
6003            }
6004        }
6005    }
6006
6007    /**
6008     * Enforces that only the system UID or root's UID can call a method exposed
6009     * via Binder.
6010     *
6011     * @param message used as message if SecurityException is thrown
6012     * @throws SecurityException if the caller is not system or root
6013     */
6014    private static final void enforceSystemOrRoot(String message) {
6015        final int uid = Binder.getCallingUid();
6016        if (uid != Process.SYSTEM_UID && uid != 0) {
6017            throw new SecurityException(message);
6018        }
6019    }
6020
6021    @Override
6022    public void performBootDexOpt() {
6023        enforceSystemOrRoot("Only the system can request dexopt be performed");
6024
6025        // Before everything else, see whether we need to fstrim.
6026        try {
6027            IMountService ms = PackageHelper.getMountService();
6028            if (ms != null) {
6029                final boolean isUpgrade = isUpgrade();
6030                boolean doTrim = isUpgrade;
6031                if (doTrim) {
6032                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6033                } else {
6034                    final long interval = android.provider.Settings.Global.getLong(
6035                            mContext.getContentResolver(),
6036                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6037                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6038                    if (interval > 0) {
6039                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6040                        if (timeSinceLast > interval) {
6041                            doTrim = true;
6042                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6043                                    + "; running immediately");
6044                        }
6045                    }
6046                }
6047                if (doTrim) {
6048                    if (!isFirstBoot()) {
6049                        try {
6050                            ActivityManagerNative.getDefault().showBootMessage(
6051                                    mContext.getResources().getString(
6052                                            R.string.android_upgrading_fstrim), true);
6053                        } catch (RemoteException e) {
6054                        }
6055                    }
6056                    ms.runMaintenance();
6057                }
6058            } else {
6059                Slog.e(TAG, "Mount service unavailable!");
6060            }
6061        } catch (RemoteException e) {
6062            // Can't happen; MountService is local
6063        }
6064
6065        final ArraySet<PackageParser.Package> pkgs;
6066        synchronized (mPackages) {
6067            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6068        }
6069
6070        if (pkgs != null) {
6071            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6072            // in case the device runs out of space.
6073            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6074            // Give priority to core apps.
6075            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6076                PackageParser.Package pkg = it.next();
6077                if (pkg.coreApp) {
6078                    if (DEBUG_DEXOPT) {
6079                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6080                    }
6081                    sortedPkgs.add(pkg);
6082                    it.remove();
6083                }
6084            }
6085            // Give priority to system apps that listen for pre boot complete.
6086            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6087            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6088            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6089                PackageParser.Package pkg = it.next();
6090                if (pkgNames.contains(pkg.packageName)) {
6091                    if (DEBUG_DEXOPT) {
6092                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6093                    }
6094                    sortedPkgs.add(pkg);
6095                    it.remove();
6096                }
6097            }
6098            // Filter out packages that aren't recently used.
6099            filterRecentlyUsedApps(pkgs);
6100            // Add all remaining apps.
6101            for (PackageParser.Package pkg : pkgs) {
6102                if (DEBUG_DEXOPT) {
6103                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6104                }
6105                sortedPkgs.add(pkg);
6106            }
6107
6108            // If we want to be lazy, filter everything that wasn't recently used.
6109            if (mLazyDexOpt) {
6110                filterRecentlyUsedApps(sortedPkgs);
6111            }
6112
6113            int i = 0;
6114            int total = sortedPkgs.size();
6115            File dataDir = Environment.getDataDirectory();
6116            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6117            if (lowThreshold == 0) {
6118                throw new IllegalStateException("Invalid low memory threshold");
6119            }
6120            for (PackageParser.Package pkg : sortedPkgs) {
6121                long usableSpace = dataDir.getUsableSpace();
6122                if (usableSpace < lowThreshold) {
6123                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6124                    break;
6125                }
6126                performBootDexOpt(pkg, ++i, total);
6127            }
6128        }
6129    }
6130
6131    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6132        // Filter out packages that aren't recently used.
6133        //
6134        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6135        // should do a full dexopt.
6136        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6137            int total = pkgs.size();
6138            int skipped = 0;
6139            long now = System.currentTimeMillis();
6140            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6141                PackageParser.Package pkg = i.next();
6142                long then = pkg.mLastPackageUsageTimeInMills;
6143                if (then + mDexOptLRUThresholdInMills < now) {
6144                    if (DEBUG_DEXOPT) {
6145                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6146                              ((then == 0) ? "never" : new Date(then)));
6147                    }
6148                    i.remove();
6149                    skipped++;
6150                }
6151            }
6152            if (DEBUG_DEXOPT) {
6153                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6154            }
6155        }
6156    }
6157
6158    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6159        List<ResolveInfo> ris = null;
6160        try {
6161            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6162                    intent, null, 0, UserHandle.USER_OWNER);
6163        } catch (RemoteException e) {
6164        }
6165        ArraySet<String> pkgNames = new ArraySet<String>();
6166        if (ris != null) {
6167            for (ResolveInfo ri : ris) {
6168                pkgNames.add(ri.activityInfo.packageName);
6169            }
6170        }
6171        return pkgNames;
6172    }
6173
6174    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6175        if (DEBUG_DEXOPT) {
6176            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6177        }
6178        if (!isFirstBoot()) {
6179            try {
6180                ActivityManagerNative.getDefault().showBootMessage(
6181                        mContext.getResources().getString(R.string.android_upgrading_apk,
6182                                curr, total), true);
6183            } catch (RemoteException e) {
6184            }
6185        }
6186        PackageParser.Package p = pkg;
6187        synchronized (mInstallLock) {
6188            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6189                    false /* force dex */, false /* defer */, true /* include dependencies */,
6190                    false /* boot complete */);
6191        }
6192    }
6193
6194    @Override
6195    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6196        return performDexOpt(packageName, instructionSet, false);
6197    }
6198
6199    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6200        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6201        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6202        if (!dexopt && !updateUsage) {
6203            // We aren't going to dexopt or update usage, so bail early.
6204            return false;
6205        }
6206        PackageParser.Package p;
6207        final String targetInstructionSet;
6208        synchronized (mPackages) {
6209            p = mPackages.get(packageName);
6210            if (p == null) {
6211                return false;
6212            }
6213            if (updateUsage) {
6214                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6215            }
6216            mPackageUsage.write(false);
6217            if (!dexopt) {
6218                // We aren't going to dexopt, so bail early.
6219                return false;
6220            }
6221
6222            targetInstructionSet = instructionSet != null ? instructionSet :
6223                    getPrimaryInstructionSet(p.applicationInfo);
6224            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6225                return false;
6226            }
6227        }
6228        long callingId = Binder.clearCallingIdentity();
6229        try {
6230            synchronized (mInstallLock) {
6231                final String[] instructionSets = new String[] { targetInstructionSet };
6232                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6233                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6234                        true /* boot complete */);
6235                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6236            }
6237        } finally {
6238            Binder.restoreCallingIdentity(callingId);
6239        }
6240    }
6241
6242    public ArraySet<String> getPackagesThatNeedDexOpt() {
6243        ArraySet<String> pkgs = null;
6244        synchronized (mPackages) {
6245            for (PackageParser.Package p : mPackages.values()) {
6246                if (DEBUG_DEXOPT) {
6247                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6248                }
6249                if (!p.mDexOptPerformed.isEmpty()) {
6250                    continue;
6251                }
6252                if (pkgs == null) {
6253                    pkgs = new ArraySet<String>();
6254                }
6255                pkgs.add(p.packageName);
6256            }
6257        }
6258        return pkgs;
6259    }
6260
6261    public void shutdown() {
6262        mPackageUsage.write(true);
6263    }
6264
6265    @Override
6266    public void forceDexOpt(String packageName) {
6267        enforceSystemOrRoot("forceDexOpt");
6268
6269        PackageParser.Package pkg;
6270        synchronized (mPackages) {
6271            pkg = mPackages.get(packageName);
6272            if (pkg == null) {
6273                throw new IllegalArgumentException("Missing package: " + packageName);
6274            }
6275        }
6276
6277        synchronized (mInstallLock) {
6278            final String[] instructionSets = new String[] {
6279                    getPrimaryInstructionSet(pkg.applicationInfo) };
6280            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6281                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6282                    true /* boot complete */);
6283            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6284                throw new IllegalStateException("Failed to dexopt: " + res);
6285            }
6286        }
6287    }
6288
6289    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6290        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6291            Slog.w(TAG, "Unable to update from " + oldPkg.name
6292                    + " to " + newPkg.packageName
6293                    + ": old package not in system partition");
6294            return false;
6295        } else if (mPackages.get(oldPkg.name) != null) {
6296            Slog.w(TAG, "Unable to update from " + oldPkg.name
6297                    + " to " + newPkg.packageName
6298                    + ": old package still exists");
6299            return false;
6300        }
6301        return true;
6302    }
6303
6304    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6305        int[] users = sUserManager.getUserIds();
6306        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6307        if (res < 0) {
6308            return res;
6309        }
6310        for (int user : users) {
6311            if (user != 0) {
6312                res = mInstaller.createUserData(volumeUuid, packageName,
6313                        UserHandle.getUid(user, uid), user, seinfo);
6314                if (res < 0) {
6315                    return res;
6316                }
6317            }
6318        }
6319        return res;
6320    }
6321
6322    private int removeDataDirsLI(String volumeUuid, String packageName) {
6323        int[] users = sUserManager.getUserIds();
6324        int res = 0;
6325        for (int user : users) {
6326            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6327            if (resInner < 0) {
6328                res = resInner;
6329            }
6330        }
6331
6332        return res;
6333    }
6334
6335    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6336        int[] users = sUserManager.getUserIds();
6337        int res = 0;
6338        for (int user : users) {
6339            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6340            if (resInner < 0) {
6341                res = resInner;
6342            }
6343        }
6344        return res;
6345    }
6346
6347    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6348            PackageParser.Package changingLib) {
6349        if (file.path != null) {
6350            usesLibraryFiles.add(file.path);
6351            return;
6352        }
6353        PackageParser.Package p = mPackages.get(file.apk);
6354        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6355            // If we are doing this while in the middle of updating a library apk,
6356            // then we need to make sure to use that new apk for determining the
6357            // dependencies here.  (We haven't yet finished committing the new apk
6358            // to the package manager state.)
6359            if (p == null || p.packageName.equals(changingLib.packageName)) {
6360                p = changingLib;
6361            }
6362        }
6363        if (p != null) {
6364            usesLibraryFiles.addAll(p.getAllCodePaths());
6365        }
6366    }
6367
6368    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6369            PackageParser.Package changingLib) throws PackageManagerException {
6370        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6371            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6372            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6373            for (int i=0; i<N; i++) {
6374                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6375                if (file == null) {
6376                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6377                            "Package " + pkg.packageName + " requires unavailable shared library "
6378                            + pkg.usesLibraries.get(i) + "; failing!");
6379                }
6380                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6381            }
6382            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6383            for (int i=0; i<N; i++) {
6384                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6385                if (file == null) {
6386                    Slog.w(TAG, "Package " + pkg.packageName
6387                            + " desires unavailable shared library "
6388                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6389                } else {
6390                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6391                }
6392            }
6393            N = usesLibraryFiles.size();
6394            if (N > 0) {
6395                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6396            } else {
6397                pkg.usesLibraryFiles = null;
6398            }
6399        }
6400    }
6401
6402    private static boolean hasString(List<String> list, List<String> which) {
6403        if (list == null) {
6404            return false;
6405        }
6406        for (int i=list.size()-1; i>=0; i--) {
6407            for (int j=which.size()-1; j>=0; j--) {
6408                if (which.get(j).equals(list.get(i))) {
6409                    return true;
6410                }
6411            }
6412        }
6413        return false;
6414    }
6415
6416    private void updateAllSharedLibrariesLPw() {
6417        for (PackageParser.Package pkg : mPackages.values()) {
6418            try {
6419                updateSharedLibrariesLPw(pkg, null);
6420            } catch (PackageManagerException e) {
6421                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6422            }
6423        }
6424    }
6425
6426    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6427            PackageParser.Package changingPkg) {
6428        ArrayList<PackageParser.Package> res = null;
6429        for (PackageParser.Package pkg : mPackages.values()) {
6430            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6431                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6432                if (res == null) {
6433                    res = new ArrayList<PackageParser.Package>();
6434                }
6435                res.add(pkg);
6436                try {
6437                    updateSharedLibrariesLPw(pkg, changingPkg);
6438                } catch (PackageManagerException e) {
6439                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6440                }
6441            }
6442        }
6443        return res;
6444    }
6445
6446    /**
6447     * Derive the value of the {@code cpuAbiOverride} based on the provided
6448     * value and an optional stored value from the package settings.
6449     */
6450    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6451        String cpuAbiOverride = null;
6452
6453        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6454            cpuAbiOverride = null;
6455        } else if (abiOverride != null) {
6456            cpuAbiOverride = abiOverride;
6457        } else if (settings != null) {
6458            cpuAbiOverride = settings.cpuAbiOverrideString;
6459        }
6460
6461        return cpuAbiOverride;
6462    }
6463
6464    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6465            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6466        boolean success = false;
6467        try {
6468            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6469                    currentTime, user);
6470            success = true;
6471            return res;
6472        } finally {
6473            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6474                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6475            }
6476        }
6477    }
6478
6479    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6480            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6481        final File scanFile = new File(pkg.codePath);
6482        if (pkg.applicationInfo.getCodePath() == null ||
6483                pkg.applicationInfo.getResourcePath() == null) {
6484            // Bail out. The resource and code paths haven't been set.
6485            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6486                    "Code and resource paths haven't been set correctly");
6487        }
6488
6489        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6490            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6491        } else {
6492            // Only allow system apps to be flagged as core apps.
6493            pkg.coreApp = false;
6494        }
6495
6496        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6497            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6498        }
6499
6500        if (mCustomResolverComponentName != null &&
6501                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6502            setUpCustomResolverActivity(pkg);
6503        }
6504
6505        if (pkg.packageName.equals("android")) {
6506            synchronized (mPackages) {
6507                if (mAndroidApplication != null) {
6508                    Slog.w(TAG, "*************************************************");
6509                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6510                    Slog.w(TAG, " file=" + scanFile);
6511                    Slog.w(TAG, "*************************************************");
6512                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6513                            "Core android package being redefined.  Skipping.");
6514                }
6515
6516                // Set up information for our fall-back user intent resolution activity.
6517                mPlatformPackage = pkg;
6518                pkg.mVersionCode = mSdkVersion;
6519                mAndroidApplication = pkg.applicationInfo;
6520
6521                if (!mResolverReplaced) {
6522                    mResolveActivity.applicationInfo = mAndroidApplication;
6523                    mResolveActivity.name = ResolverActivity.class.getName();
6524                    mResolveActivity.packageName = mAndroidApplication.packageName;
6525                    mResolveActivity.processName = "system:ui";
6526                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6527                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6528                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6529                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6530                    mResolveActivity.exported = true;
6531                    mResolveActivity.enabled = true;
6532                    mResolveInfo.activityInfo = mResolveActivity;
6533                    mResolveInfo.priority = 0;
6534                    mResolveInfo.preferredOrder = 0;
6535                    mResolveInfo.match = 0;
6536                    mResolveComponentName = new ComponentName(
6537                            mAndroidApplication.packageName, mResolveActivity.name);
6538                }
6539            }
6540        }
6541
6542        if (DEBUG_PACKAGE_SCANNING) {
6543            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6544                Log.d(TAG, "Scanning package " + pkg.packageName);
6545        }
6546
6547        if (mPackages.containsKey(pkg.packageName)
6548                || mSharedLibraries.containsKey(pkg.packageName)) {
6549            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6550                    "Application package " + pkg.packageName
6551                    + " already installed.  Skipping duplicate.");
6552        }
6553
6554        // If we're only installing presumed-existing packages, require that the
6555        // scanned APK is both already known and at the path previously established
6556        // for it.  Previously unknown packages we pick up normally, but if we have an
6557        // a priori expectation about this package's install presence, enforce it.
6558        // With a singular exception for new system packages. When an OTA contains
6559        // a new system package, we allow the codepath to change from a system location
6560        // to the user-installed location. If we don't allow this change, any newer,
6561        // user-installed version of the application will be ignored.
6562        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6563            if (mExpectingBetter.containsKey(pkg.packageName)) {
6564                logCriticalInfo(Log.WARN,
6565                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6566            } else {
6567                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6568                if (known != null) {
6569                    if (DEBUG_PACKAGE_SCANNING) {
6570                        Log.d(TAG, "Examining " + pkg.codePath
6571                                + " and requiring known paths " + known.codePathString
6572                                + " & " + known.resourcePathString);
6573                    }
6574                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6575                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6576                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6577                                "Application package " + pkg.packageName
6578                                + " found at " + pkg.applicationInfo.getCodePath()
6579                                + " but expected at " + known.codePathString + "; ignoring.");
6580                    }
6581                }
6582            }
6583        }
6584
6585        // Initialize package source and resource directories
6586        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6587        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6588
6589        SharedUserSetting suid = null;
6590        PackageSetting pkgSetting = null;
6591
6592        if (!isSystemApp(pkg)) {
6593            // Only system apps can use these features.
6594            pkg.mOriginalPackages = null;
6595            pkg.mRealPackage = null;
6596            pkg.mAdoptPermissions = null;
6597        }
6598
6599        // writer
6600        synchronized (mPackages) {
6601            if (pkg.mSharedUserId != null) {
6602                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6603                if (suid == null) {
6604                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6605                            "Creating application package " + pkg.packageName
6606                            + " for shared user failed");
6607                }
6608                if (DEBUG_PACKAGE_SCANNING) {
6609                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6610                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6611                                + "): packages=" + suid.packages);
6612                }
6613            }
6614
6615            // Check if we are renaming from an original package name.
6616            PackageSetting origPackage = null;
6617            String realName = null;
6618            if (pkg.mOriginalPackages != null) {
6619                // This package may need to be renamed to a previously
6620                // installed name.  Let's check on that...
6621                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6622                if (pkg.mOriginalPackages.contains(renamed)) {
6623                    // This package had originally been installed as the
6624                    // original name, and we have already taken care of
6625                    // transitioning to the new one.  Just update the new
6626                    // one to continue using the old name.
6627                    realName = pkg.mRealPackage;
6628                    if (!pkg.packageName.equals(renamed)) {
6629                        // Callers into this function may have already taken
6630                        // care of renaming the package; only do it here if
6631                        // it is not already done.
6632                        pkg.setPackageName(renamed);
6633                    }
6634
6635                } else {
6636                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6637                        if ((origPackage = mSettings.peekPackageLPr(
6638                                pkg.mOriginalPackages.get(i))) != null) {
6639                            // We do have the package already installed under its
6640                            // original name...  should we use it?
6641                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6642                                // New package is not compatible with original.
6643                                origPackage = null;
6644                                continue;
6645                            } else if (origPackage.sharedUser != null) {
6646                                // Make sure uid is compatible between packages.
6647                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6648                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6649                                            + " to " + pkg.packageName + ": old uid "
6650                                            + origPackage.sharedUser.name
6651                                            + " differs from " + pkg.mSharedUserId);
6652                                    origPackage = null;
6653                                    continue;
6654                                }
6655                            } else {
6656                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6657                                        + pkg.packageName + " to old name " + origPackage.name);
6658                            }
6659                            break;
6660                        }
6661                    }
6662                }
6663            }
6664
6665            if (mTransferedPackages.contains(pkg.packageName)) {
6666                Slog.w(TAG, "Package " + pkg.packageName
6667                        + " was transferred to another, but its .apk remains");
6668            }
6669
6670            // Just create the setting, don't add it yet. For already existing packages
6671            // the PkgSetting exists already and doesn't have to be created.
6672            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6673                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6674                    pkg.applicationInfo.primaryCpuAbi,
6675                    pkg.applicationInfo.secondaryCpuAbi,
6676                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6677                    user, false);
6678            if (pkgSetting == null) {
6679                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6680                        "Creating application package " + pkg.packageName + " failed");
6681            }
6682
6683            if (pkgSetting.origPackage != null) {
6684                // If we are first transitioning from an original package,
6685                // fix up the new package's name now.  We need to do this after
6686                // looking up the package under its new name, so getPackageLP
6687                // can take care of fiddling things correctly.
6688                pkg.setPackageName(origPackage.name);
6689
6690                // File a report about this.
6691                String msg = "New package " + pkgSetting.realName
6692                        + " renamed to replace old package " + pkgSetting.name;
6693                reportSettingsProblem(Log.WARN, msg);
6694
6695                // Make a note of it.
6696                mTransferedPackages.add(origPackage.name);
6697
6698                // No longer need to retain this.
6699                pkgSetting.origPackage = null;
6700            }
6701
6702            if (realName != null) {
6703                // Make a note of it.
6704                mTransferedPackages.add(pkg.packageName);
6705            }
6706
6707            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6708                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6709            }
6710
6711            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6712                // Check all shared libraries and map to their actual file path.
6713                // We only do this here for apps not on a system dir, because those
6714                // are the only ones that can fail an install due to this.  We
6715                // will take care of the system apps by updating all of their
6716                // library paths after the scan is done.
6717                updateSharedLibrariesLPw(pkg, null);
6718            }
6719
6720            if (mFoundPolicyFile) {
6721                SELinuxMMAC.assignSeinfoValue(pkg);
6722            }
6723
6724            pkg.applicationInfo.uid = pkgSetting.appId;
6725            pkg.mExtras = pkgSetting;
6726            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6727                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6728                    // We just determined the app is signed correctly, so bring
6729                    // over the latest parsed certs.
6730                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6731                } else {
6732                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6733                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6734                                "Package " + pkg.packageName + " upgrade keys do not match the "
6735                                + "previously installed version");
6736                    } else {
6737                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6738                        String msg = "System package " + pkg.packageName
6739                            + " signature changed; retaining data.";
6740                        reportSettingsProblem(Log.WARN, msg);
6741                    }
6742                }
6743            } else {
6744                try {
6745                    verifySignaturesLP(pkgSetting, pkg);
6746                    // We just determined the app is signed correctly, so bring
6747                    // over the latest parsed certs.
6748                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6749                } catch (PackageManagerException e) {
6750                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6751                        throw e;
6752                    }
6753                    // The signature has changed, but this package is in the system
6754                    // image...  let's recover!
6755                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6756                    // However...  if this package is part of a shared user, but it
6757                    // doesn't match the signature of the shared user, let's fail.
6758                    // What this means is that you can't change the signatures
6759                    // associated with an overall shared user, which doesn't seem all
6760                    // that unreasonable.
6761                    if (pkgSetting.sharedUser != null) {
6762                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6763                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6764                            throw new PackageManagerException(
6765                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6766                                            "Signature mismatch for shared user : "
6767                                            + pkgSetting.sharedUser);
6768                        }
6769                    }
6770                    // File a report about this.
6771                    String msg = "System package " + pkg.packageName
6772                        + " signature changed; retaining data.";
6773                    reportSettingsProblem(Log.WARN, msg);
6774                }
6775            }
6776            // Verify that this new package doesn't have any content providers
6777            // that conflict with existing packages.  Only do this if the
6778            // package isn't already installed, since we don't want to break
6779            // things that are installed.
6780            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6781                final int N = pkg.providers.size();
6782                int i;
6783                for (i=0; i<N; i++) {
6784                    PackageParser.Provider p = pkg.providers.get(i);
6785                    if (p.info.authority != null) {
6786                        String names[] = p.info.authority.split(";");
6787                        for (int j = 0; j < names.length; j++) {
6788                            if (mProvidersByAuthority.containsKey(names[j])) {
6789                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6790                                final String otherPackageName =
6791                                        ((other != null && other.getComponentName() != null) ?
6792                                                other.getComponentName().getPackageName() : "?");
6793                                throw new PackageManagerException(
6794                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6795                                                "Can't install because provider name " + names[j]
6796                                                + " (in package " + pkg.applicationInfo.packageName
6797                                                + ") is already used by " + otherPackageName);
6798                            }
6799                        }
6800                    }
6801                }
6802            }
6803
6804            if (pkg.mAdoptPermissions != null) {
6805                // This package wants to adopt ownership of permissions from
6806                // another package.
6807                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6808                    final String origName = pkg.mAdoptPermissions.get(i);
6809                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6810                    if (orig != null) {
6811                        if (verifyPackageUpdateLPr(orig, pkg)) {
6812                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6813                                    + pkg.packageName);
6814                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6815                        }
6816                    }
6817                }
6818            }
6819        }
6820
6821        final String pkgName = pkg.packageName;
6822
6823        final long scanFileTime = scanFile.lastModified();
6824        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6825        pkg.applicationInfo.processName = fixProcessName(
6826                pkg.applicationInfo.packageName,
6827                pkg.applicationInfo.processName,
6828                pkg.applicationInfo.uid);
6829
6830        File dataPath;
6831        if (mPlatformPackage == pkg) {
6832            // The system package is special.
6833            dataPath = new File(Environment.getDataDirectory(), "system");
6834
6835            pkg.applicationInfo.dataDir = dataPath.getPath();
6836
6837        } else {
6838            // This is a normal package, need to make its data directory.
6839            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6840                    UserHandle.USER_OWNER, pkg.packageName);
6841
6842            boolean uidError = false;
6843            if (dataPath.exists()) {
6844                int currentUid = 0;
6845                try {
6846                    StructStat stat = Os.stat(dataPath.getPath());
6847                    currentUid = stat.st_uid;
6848                } catch (ErrnoException e) {
6849                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6850                }
6851
6852                // If we have mismatched owners for the data path, we have a problem.
6853                if (currentUid != pkg.applicationInfo.uid) {
6854                    boolean recovered = false;
6855                    if (currentUid == 0) {
6856                        // The directory somehow became owned by root.  Wow.
6857                        // This is probably because the system was stopped while
6858                        // installd was in the middle of messing with its libs
6859                        // directory.  Ask installd to fix that.
6860                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6861                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6862                        if (ret >= 0) {
6863                            recovered = true;
6864                            String msg = "Package " + pkg.packageName
6865                                    + " unexpectedly changed to uid 0; recovered to " +
6866                                    + pkg.applicationInfo.uid;
6867                            reportSettingsProblem(Log.WARN, msg);
6868                        }
6869                    }
6870                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6871                            || (scanFlags&SCAN_BOOTING) != 0)) {
6872                        // If this is a system app, we can at least delete its
6873                        // current data so the application will still work.
6874                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6875                        if (ret >= 0) {
6876                            // TODO: Kill the processes first
6877                            // Old data gone!
6878                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6879                                    ? "System package " : "Third party package ";
6880                            String msg = prefix + pkg.packageName
6881                                    + " has changed from uid: "
6882                                    + currentUid + " to "
6883                                    + pkg.applicationInfo.uid + "; old data erased";
6884                            reportSettingsProblem(Log.WARN, msg);
6885                            recovered = true;
6886
6887                            // And now re-install the app.
6888                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6889                                    pkg.applicationInfo.seinfo);
6890                            if (ret == -1) {
6891                                // Ack should not happen!
6892                                msg = prefix + pkg.packageName
6893                                        + " could not have data directory re-created after delete.";
6894                                reportSettingsProblem(Log.WARN, msg);
6895                                throw new PackageManagerException(
6896                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6897                            }
6898                        }
6899                        if (!recovered) {
6900                            mHasSystemUidErrors = true;
6901                        }
6902                    } else if (!recovered) {
6903                        // If we allow this install to proceed, we will be broken.
6904                        // Abort, abort!
6905                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6906                                "scanPackageLI");
6907                    }
6908                    if (!recovered) {
6909                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6910                            + pkg.applicationInfo.uid + "/fs_"
6911                            + currentUid;
6912                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6913                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6914                        String msg = "Package " + pkg.packageName
6915                                + " has mismatched uid: "
6916                                + currentUid + " on disk, "
6917                                + pkg.applicationInfo.uid + " in settings";
6918                        // writer
6919                        synchronized (mPackages) {
6920                            mSettings.mReadMessages.append(msg);
6921                            mSettings.mReadMessages.append('\n');
6922                            uidError = true;
6923                            if (!pkgSetting.uidError) {
6924                                reportSettingsProblem(Log.ERROR, msg);
6925                            }
6926                        }
6927                    }
6928                }
6929                pkg.applicationInfo.dataDir = dataPath.getPath();
6930                if (mShouldRestoreconData) {
6931                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6932                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6933                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6934                }
6935            } else {
6936                if (DEBUG_PACKAGE_SCANNING) {
6937                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6938                        Log.v(TAG, "Want this data dir: " + dataPath);
6939                }
6940                //invoke installer to do the actual installation
6941                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6942                        pkg.applicationInfo.seinfo);
6943                if (ret < 0) {
6944                    // Error from installer
6945                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6946                            "Unable to create data dirs [errorCode=" + ret + "]");
6947                }
6948
6949                if (dataPath.exists()) {
6950                    pkg.applicationInfo.dataDir = dataPath.getPath();
6951                } else {
6952                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6953                    pkg.applicationInfo.dataDir = null;
6954                }
6955            }
6956
6957            pkgSetting.uidError = uidError;
6958        }
6959
6960        final String path = scanFile.getPath();
6961        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6962
6963        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6964            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6965
6966            // Some system apps still use directory structure for native libraries
6967            // in which case we might end up not detecting abi solely based on apk
6968            // structure. Try to detect abi based on directory structure.
6969            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6970                    pkg.applicationInfo.primaryCpuAbi == null) {
6971                setBundledAppAbisAndRoots(pkg, pkgSetting);
6972                setNativeLibraryPaths(pkg);
6973            }
6974
6975        } else {
6976            if ((scanFlags & SCAN_MOVE) != 0) {
6977                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6978                // but we already have this packages package info in the PackageSetting. We just
6979                // use that and derive the native library path based on the new codepath.
6980                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6981                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6982            }
6983
6984            // Set native library paths again. For moves, the path will be updated based on the
6985            // ABIs we've determined above. For non-moves, the path will be updated based on the
6986            // ABIs we determined during compilation, but the path will depend on the final
6987            // package path (after the rename away from the stage path).
6988            setNativeLibraryPaths(pkg);
6989        }
6990
6991        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6992        final int[] userIds = sUserManager.getUserIds();
6993        synchronized (mInstallLock) {
6994            // Make sure all user data directories are ready to roll; we're okay
6995            // if they already exist
6996            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6997                for (int userId : userIds) {
6998                    if (userId != 0) {
6999                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7000                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7001                                pkg.applicationInfo.seinfo);
7002                    }
7003                }
7004            }
7005
7006            // Create a native library symlink only if we have native libraries
7007            // and if the native libraries are 32 bit libraries. We do not provide
7008            // this symlink for 64 bit libraries.
7009            if (pkg.applicationInfo.primaryCpuAbi != null &&
7010                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7011                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7012                for (int userId : userIds) {
7013                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7014                            nativeLibPath, userId) < 0) {
7015                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7016                                "Failed linking native library dir (user=" + userId + ")");
7017                    }
7018                }
7019            }
7020        }
7021
7022        // This is a special case for the "system" package, where the ABI is
7023        // dictated by the zygote configuration (and init.rc). We should keep track
7024        // of this ABI so that we can deal with "normal" applications that run under
7025        // the same UID correctly.
7026        if (mPlatformPackage == pkg) {
7027            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7028                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7029        }
7030
7031        // If there's a mismatch between the abi-override in the package setting
7032        // and the abiOverride specified for the install. Warn about this because we
7033        // would've already compiled the app without taking the package setting into
7034        // account.
7035        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7036            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7037                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7038                        " for package: " + pkg.packageName);
7039            }
7040        }
7041
7042        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7043        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7044        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7045
7046        // Copy the derived override back to the parsed package, so that we can
7047        // update the package settings accordingly.
7048        pkg.cpuAbiOverride = cpuAbiOverride;
7049
7050        if (DEBUG_ABI_SELECTION) {
7051            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7052                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7053                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7054        }
7055
7056        // Push the derived path down into PackageSettings so we know what to
7057        // clean up at uninstall time.
7058        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7059
7060        if (DEBUG_ABI_SELECTION) {
7061            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7062                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7063                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7064        }
7065
7066        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7067            // We don't do this here during boot because we can do it all
7068            // at once after scanning all existing packages.
7069            //
7070            // We also do this *before* we perform dexopt on this package, so that
7071            // we can avoid redundant dexopts, and also to make sure we've got the
7072            // code and package path correct.
7073            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7074                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7075        }
7076
7077        if ((scanFlags & SCAN_NO_DEX) == 0) {
7078            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7079                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7080                    (scanFlags & SCAN_BOOTING) == 0);
7081            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7082                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7083            }
7084        }
7085        if (mFactoryTest && pkg.requestedPermissions.contains(
7086                android.Manifest.permission.FACTORY_TEST)) {
7087            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7088        }
7089
7090        ArrayList<PackageParser.Package> clientLibPkgs = null;
7091
7092        // writer
7093        synchronized (mPackages) {
7094            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7095                // Only system apps can add new shared libraries.
7096                if (pkg.libraryNames != null) {
7097                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7098                        String name = pkg.libraryNames.get(i);
7099                        boolean allowed = false;
7100                        if (pkg.isUpdatedSystemApp()) {
7101                            // New library entries can only be added through the
7102                            // system image.  This is important to get rid of a lot
7103                            // of nasty edge cases: for example if we allowed a non-
7104                            // system update of the app to add a library, then uninstalling
7105                            // the update would make the library go away, and assumptions
7106                            // we made such as through app install filtering would now
7107                            // have allowed apps on the device which aren't compatible
7108                            // with it.  Better to just have the restriction here, be
7109                            // conservative, and create many fewer cases that can negatively
7110                            // impact the user experience.
7111                            final PackageSetting sysPs = mSettings
7112                                    .getDisabledSystemPkgLPr(pkg.packageName);
7113                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7114                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7115                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7116                                        allowed = true;
7117                                        allowed = true;
7118                                        break;
7119                                    }
7120                                }
7121                            }
7122                        } else {
7123                            allowed = true;
7124                        }
7125                        if (allowed) {
7126                            if (!mSharedLibraries.containsKey(name)) {
7127                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7128                            } else if (!name.equals(pkg.packageName)) {
7129                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7130                                        + name + " already exists; skipping");
7131                            }
7132                        } else {
7133                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7134                                    + name + " that is not declared on system image; skipping");
7135                        }
7136                    }
7137                    if ((scanFlags&SCAN_BOOTING) == 0) {
7138                        // If we are not booting, we need to update any applications
7139                        // that are clients of our shared library.  If we are booting,
7140                        // this will all be done once the scan is complete.
7141                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7142                    }
7143                }
7144            }
7145        }
7146
7147        // We also need to dexopt any apps that are dependent on this library.  Note that
7148        // if these fail, we should abort the install since installing the library will
7149        // result in some apps being broken.
7150        if (clientLibPkgs != null) {
7151            if ((scanFlags & SCAN_NO_DEX) == 0) {
7152                for (int i = 0; i < clientLibPkgs.size(); i++) {
7153                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7154                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7155                            null /* instruction sets */, forceDex,
7156                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7157                            (scanFlags & SCAN_BOOTING) == 0);
7158                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7159                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7160                                "scanPackageLI failed to dexopt clientLibPkgs");
7161                    }
7162                }
7163            }
7164        }
7165
7166        // Request the ActivityManager to kill the process(only for existing packages)
7167        // so that we do not end up in a confused state while the user is still using the older
7168        // version of the application while the new one gets installed.
7169        if ((scanFlags & SCAN_REPLACING) != 0) {
7170            killApplication(pkg.applicationInfo.packageName,
7171                        pkg.applicationInfo.uid, "replace pkg");
7172        }
7173
7174        // Also need to kill any apps that are dependent on the library.
7175        if (clientLibPkgs != null) {
7176            for (int i=0; i<clientLibPkgs.size(); i++) {
7177                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7178                killApplication(clientPkg.applicationInfo.packageName,
7179                        clientPkg.applicationInfo.uid, "update lib");
7180            }
7181        }
7182
7183        // Make sure we're not adding any bogus keyset info
7184        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7185        ksms.assertScannedPackageValid(pkg);
7186
7187        // writer
7188        synchronized (mPackages) {
7189            // We don't expect installation to fail beyond this point
7190
7191            // Add the new setting to mSettings
7192            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7193            // Add the new setting to mPackages
7194            mPackages.put(pkg.applicationInfo.packageName, pkg);
7195            // Make sure we don't accidentally delete its data.
7196            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7197            while (iter.hasNext()) {
7198                PackageCleanItem item = iter.next();
7199                if (pkgName.equals(item.packageName)) {
7200                    iter.remove();
7201                }
7202            }
7203
7204            // Take care of first install / last update times.
7205            if (currentTime != 0) {
7206                if (pkgSetting.firstInstallTime == 0) {
7207                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7208                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7209                    pkgSetting.lastUpdateTime = currentTime;
7210                }
7211            } else if (pkgSetting.firstInstallTime == 0) {
7212                // We need *something*.  Take time time stamp of the file.
7213                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7214            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7215                if (scanFileTime != pkgSetting.timeStamp) {
7216                    // A package on the system image has changed; consider this
7217                    // to be an update.
7218                    pkgSetting.lastUpdateTime = scanFileTime;
7219                }
7220            }
7221
7222            // Add the package's KeySets to the global KeySetManagerService
7223            ksms.addScannedPackageLPw(pkg);
7224
7225            int N = pkg.providers.size();
7226            StringBuilder r = null;
7227            int i;
7228            for (i=0; i<N; i++) {
7229                PackageParser.Provider p = pkg.providers.get(i);
7230                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7231                        p.info.processName, pkg.applicationInfo.uid);
7232                mProviders.addProvider(p);
7233                p.syncable = p.info.isSyncable;
7234                if (p.info.authority != null) {
7235                    String names[] = p.info.authority.split(";");
7236                    p.info.authority = null;
7237                    for (int j = 0; j < names.length; j++) {
7238                        if (j == 1 && p.syncable) {
7239                            // We only want the first authority for a provider to possibly be
7240                            // syncable, so if we already added this provider using a different
7241                            // authority clear the syncable flag. We copy the provider before
7242                            // changing it because the mProviders object contains a reference
7243                            // to a provider that we don't want to change.
7244                            // Only do this for the second authority since the resulting provider
7245                            // object can be the same for all future authorities for this provider.
7246                            p = new PackageParser.Provider(p);
7247                            p.syncable = false;
7248                        }
7249                        if (!mProvidersByAuthority.containsKey(names[j])) {
7250                            mProvidersByAuthority.put(names[j], p);
7251                            if (p.info.authority == null) {
7252                                p.info.authority = names[j];
7253                            } else {
7254                                p.info.authority = p.info.authority + ";" + names[j];
7255                            }
7256                            if (DEBUG_PACKAGE_SCANNING) {
7257                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7258                                    Log.d(TAG, "Registered content provider: " + names[j]
7259                                            + ", className = " + p.info.name + ", isSyncable = "
7260                                            + p.info.isSyncable);
7261                            }
7262                        } else {
7263                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7264                            Slog.w(TAG, "Skipping provider name " + names[j] +
7265                                    " (in package " + pkg.applicationInfo.packageName +
7266                                    "): name already used by "
7267                                    + ((other != null && other.getComponentName() != null)
7268                                            ? other.getComponentName().getPackageName() : "?"));
7269                        }
7270                    }
7271                }
7272                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7273                    if (r == null) {
7274                        r = new StringBuilder(256);
7275                    } else {
7276                        r.append(' ');
7277                    }
7278                    r.append(p.info.name);
7279                }
7280            }
7281            if (r != null) {
7282                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7283            }
7284
7285            N = pkg.services.size();
7286            r = null;
7287            for (i=0; i<N; i++) {
7288                PackageParser.Service s = pkg.services.get(i);
7289                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7290                        s.info.processName, pkg.applicationInfo.uid);
7291                mServices.addService(s);
7292                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7293                    if (r == null) {
7294                        r = new StringBuilder(256);
7295                    } else {
7296                        r.append(' ');
7297                    }
7298                    r.append(s.info.name);
7299                }
7300            }
7301            if (r != null) {
7302                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7303            }
7304
7305            N = pkg.receivers.size();
7306            r = null;
7307            for (i=0; i<N; i++) {
7308                PackageParser.Activity a = pkg.receivers.get(i);
7309                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7310                        a.info.processName, pkg.applicationInfo.uid);
7311                mReceivers.addActivity(a, "receiver");
7312                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7313                    if (r == null) {
7314                        r = new StringBuilder(256);
7315                    } else {
7316                        r.append(' ');
7317                    }
7318                    r.append(a.info.name);
7319                }
7320            }
7321            if (r != null) {
7322                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7323            }
7324
7325            N = pkg.activities.size();
7326            r = null;
7327            for (i=0; i<N; i++) {
7328                PackageParser.Activity a = pkg.activities.get(i);
7329                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7330                        a.info.processName, pkg.applicationInfo.uid);
7331                mActivities.addActivity(a, "activity");
7332                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7333                    if (r == null) {
7334                        r = new StringBuilder(256);
7335                    } else {
7336                        r.append(' ');
7337                    }
7338                    r.append(a.info.name);
7339                }
7340            }
7341            if (r != null) {
7342                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7343            }
7344
7345            N = pkg.permissionGroups.size();
7346            r = null;
7347            for (i=0; i<N; i++) {
7348                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7349                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7350                if (cur == null) {
7351                    mPermissionGroups.put(pg.info.name, pg);
7352                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7353                        if (r == null) {
7354                            r = new StringBuilder(256);
7355                        } else {
7356                            r.append(' ');
7357                        }
7358                        r.append(pg.info.name);
7359                    }
7360                } else {
7361                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7362                            + pg.info.packageName + " ignored: original from "
7363                            + cur.info.packageName);
7364                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7365                        if (r == null) {
7366                            r = new StringBuilder(256);
7367                        } else {
7368                            r.append(' ');
7369                        }
7370                        r.append("DUP:");
7371                        r.append(pg.info.name);
7372                    }
7373                }
7374            }
7375            if (r != null) {
7376                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7377            }
7378
7379            N = pkg.permissions.size();
7380            r = null;
7381            for (i=0; i<N; i++) {
7382                PackageParser.Permission p = pkg.permissions.get(i);
7383
7384                // Assume by default that we did not install this permission into the system.
7385                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7386
7387                // Now that permission groups have a special meaning, we ignore permission
7388                // groups for legacy apps to prevent unexpected behavior. In particular,
7389                // permissions for one app being granted to someone just becuase they happen
7390                // to be in a group defined by another app (before this had no implications).
7391                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7392                    p.group = mPermissionGroups.get(p.info.group);
7393                    // Warn for a permission in an unknown group.
7394                    if (p.info.group != null && p.group == null) {
7395                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7396                                + p.info.packageName + " in an unknown group " + p.info.group);
7397                    }
7398                }
7399
7400                ArrayMap<String, BasePermission> permissionMap =
7401                        p.tree ? mSettings.mPermissionTrees
7402                                : mSettings.mPermissions;
7403                BasePermission bp = permissionMap.get(p.info.name);
7404
7405                // Allow system apps to redefine non-system permissions
7406                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7407                    final boolean currentOwnerIsSystem = (bp.perm != null
7408                            && isSystemApp(bp.perm.owner));
7409                    if (isSystemApp(p.owner)) {
7410                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7411                            // It's a built-in permission and no owner, take ownership now
7412                            bp.packageSetting = pkgSetting;
7413                            bp.perm = p;
7414                            bp.uid = pkg.applicationInfo.uid;
7415                            bp.sourcePackage = p.info.packageName;
7416                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7417                        } else if (!currentOwnerIsSystem) {
7418                            String msg = "New decl " + p.owner + " of permission  "
7419                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7420                            reportSettingsProblem(Log.WARN, msg);
7421                            bp = null;
7422                        }
7423                    }
7424                }
7425
7426                if (bp == null) {
7427                    bp = new BasePermission(p.info.name, p.info.packageName,
7428                            BasePermission.TYPE_NORMAL);
7429                    permissionMap.put(p.info.name, bp);
7430                }
7431
7432                if (bp.perm == null) {
7433                    if (bp.sourcePackage == null
7434                            || bp.sourcePackage.equals(p.info.packageName)) {
7435                        BasePermission tree = findPermissionTreeLP(p.info.name);
7436                        if (tree == null
7437                                || tree.sourcePackage.equals(p.info.packageName)) {
7438                            bp.packageSetting = pkgSetting;
7439                            bp.perm = p;
7440                            bp.uid = pkg.applicationInfo.uid;
7441                            bp.sourcePackage = p.info.packageName;
7442                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7443                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7444                                if (r == null) {
7445                                    r = new StringBuilder(256);
7446                                } else {
7447                                    r.append(' ');
7448                                }
7449                                r.append(p.info.name);
7450                            }
7451                        } else {
7452                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7453                                    + p.info.packageName + " ignored: base tree "
7454                                    + tree.name + " is from package "
7455                                    + tree.sourcePackage);
7456                        }
7457                    } else {
7458                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7459                                + p.info.packageName + " ignored: original from "
7460                                + bp.sourcePackage);
7461                    }
7462                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7463                    if (r == null) {
7464                        r = new StringBuilder(256);
7465                    } else {
7466                        r.append(' ');
7467                    }
7468                    r.append("DUP:");
7469                    r.append(p.info.name);
7470                }
7471                if (bp.perm == p) {
7472                    bp.protectionLevel = p.info.protectionLevel;
7473                }
7474            }
7475
7476            if (r != null) {
7477                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7478            }
7479
7480            N = pkg.instrumentation.size();
7481            r = null;
7482            for (i=0; i<N; i++) {
7483                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7484                a.info.packageName = pkg.applicationInfo.packageName;
7485                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7486                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7487                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7488                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7489                a.info.dataDir = pkg.applicationInfo.dataDir;
7490
7491                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7492                // need other information about the application, like the ABI and what not ?
7493                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7494                mInstrumentation.put(a.getComponentName(), a);
7495                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7496                    if (r == null) {
7497                        r = new StringBuilder(256);
7498                    } else {
7499                        r.append(' ');
7500                    }
7501                    r.append(a.info.name);
7502                }
7503            }
7504            if (r != null) {
7505                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7506            }
7507
7508            if (pkg.protectedBroadcasts != null) {
7509                N = pkg.protectedBroadcasts.size();
7510                for (i=0; i<N; i++) {
7511                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7512                }
7513            }
7514
7515            pkgSetting.setTimeStamp(scanFileTime);
7516
7517            // Create idmap files for pairs of (packages, overlay packages).
7518            // Note: "android", ie framework-res.apk, is handled by native layers.
7519            if (pkg.mOverlayTarget != null) {
7520                // This is an overlay package.
7521                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7522                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7523                        mOverlays.put(pkg.mOverlayTarget,
7524                                new ArrayMap<String, PackageParser.Package>());
7525                    }
7526                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7527                    map.put(pkg.packageName, pkg);
7528                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7529                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7530                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7531                                "scanPackageLI failed to createIdmap");
7532                    }
7533                }
7534            } else if (mOverlays.containsKey(pkg.packageName) &&
7535                    !pkg.packageName.equals("android")) {
7536                // This is a regular package, with one or more known overlay packages.
7537                createIdmapsForPackageLI(pkg);
7538            }
7539        }
7540
7541        return pkg;
7542    }
7543
7544    /**
7545     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7546     * is derived purely on the basis of the contents of {@code scanFile} and
7547     * {@code cpuAbiOverride}.
7548     *
7549     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7550     */
7551    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7552                                 String cpuAbiOverride, boolean extractLibs)
7553            throws PackageManagerException {
7554        // TODO: We can probably be smarter about this stuff. For installed apps,
7555        // we can calculate this information at install time once and for all. For
7556        // system apps, we can probably assume that this information doesn't change
7557        // after the first boot scan. As things stand, we do lots of unnecessary work.
7558
7559        // Give ourselves some initial paths; we'll come back for another
7560        // pass once we've determined ABI below.
7561        setNativeLibraryPaths(pkg);
7562
7563        // We would never need to extract libs for forward-locked and external packages,
7564        // since the container service will do it for us. We shouldn't attempt to
7565        // extract libs from system app when it was not updated.
7566        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7567                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7568            extractLibs = false;
7569        }
7570
7571        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7572        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7573
7574        NativeLibraryHelper.Handle handle = null;
7575        try {
7576            handle = NativeLibraryHelper.Handle.create(scanFile);
7577            // TODO(multiArch): This can be null for apps that didn't go through the
7578            // usual installation process. We can calculate it again, like we
7579            // do during install time.
7580            //
7581            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7582            // unnecessary.
7583            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7584
7585            // Null out the abis so that they can be recalculated.
7586            pkg.applicationInfo.primaryCpuAbi = null;
7587            pkg.applicationInfo.secondaryCpuAbi = null;
7588            if (isMultiArch(pkg.applicationInfo)) {
7589                // Warn if we've set an abiOverride for multi-lib packages..
7590                // By definition, we need to copy both 32 and 64 bit libraries for
7591                // such packages.
7592                if (pkg.cpuAbiOverride != null
7593                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7594                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7595                }
7596
7597                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7598                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7599                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7600                    if (extractLibs) {
7601                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7602                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7603                                useIsaSpecificSubdirs);
7604                    } else {
7605                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7606                    }
7607                }
7608
7609                maybeThrowExceptionForMultiArchCopy(
7610                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7611
7612                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7613                    if (extractLibs) {
7614                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7615                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7616                                useIsaSpecificSubdirs);
7617                    } else {
7618                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7619                    }
7620                }
7621
7622                maybeThrowExceptionForMultiArchCopy(
7623                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7624
7625                if (abi64 >= 0) {
7626                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7627                }
7628
7629                if (abi32 >= 0) {
7630                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7631                    if (abi64 >= 0) {
7632                        pkg.applicationInfo.secondaryCpuAbi = abi;
7633                    } else {
7634                        pkg.applicationInfo.primaryCpuAbi = abi;
7635                    }
7636                }
7637            } else {
7638                String[] abiList = (cpuAbiOverride != null) ?
7639                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7640
7641                // Enable gross and lame hacks for apps that are built with old
7642                // SDK tools. We must scan their APKs for renderscript bitcode and
7643                // not launch them if it's present. Don't bother checking on devices
7644                // that don't have 64 bit support.
7645                boolean needsRenderScriptOverride = false;
7646                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7647                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7648                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7649                    needsRenderScriptOverride = true;
7650                }
7651
7652                final int copyRet;
7653                if (extractLibs) {
7654                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7655                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7656                } else {
7657                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7658                }
7659
7660                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7661                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7662                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7663                }
7664
7665                if (copyRet >= 0) {
7666                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7667                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7668                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7669                } else if (needsRenderScriptOverride) {
7670                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7671                }
7672            }
7673        } catch (IOException ioe) {
7674            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7675        } finally {
7676            IoUtils.closeQuietly(handle);
7677        }
7678
7679        // Now that we've calculated the ABIs and determined if it's an internal app,
7680        // we will go ahead and populate the nativeLibraryPath.
7681        setNativeLibraryPaths(pkg);
7682    }
7683
7684    /**
7685     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7686     * i.e, so that all packages can be run inside a single process if required.
7687     *
7688     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7689     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7690     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7691     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7692     * updating a package that belongs to a shared user.
7693     *
7694     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7695     * adds unnecessary complexity.
7696     */
7697    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7698            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7699            boolean bootComplete) {
7700        String requiredInstructionSet = null;
7701        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7702            requiredInstructionSet = VMRuntime.getInstructionSet(
7703                     scannedPackage.applicationInfo.primaryCpuAbi);
7704        }
7705
7706        PackageSetting requirer = null;
7707        for (PackageSetting ps : packagesForUser) {
7708            // If packagesForUser contains scannedPackage, we skip it. This will happen
7709            // when scannedPackage is an update of an existing package. Without this check,
7710            // we will never be able to change the ABI of any package belonging to a shared
7711            // user, even if it's compatible with other packages.
7712            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7713                if (ps.primaryCpuAbiString == null) {
7714                    continue;
7715                }
7716
7717                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7718                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7719                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7720                    // this but there's not much we can do.
7721                    String errorMessage = "Instruction set mismatch, "
7722                            + ((requirer == null) ? "[caller]" : requirer)
7723                            + " requires " + requiredInstructionSet + " whereas " + ps
7724                            + " requires " + instructionSet;
7725                    Slog.w(TAG, errorMessage);
7726                }
7727
7728                if (requiredInstructionSet == null) {
7729                    requiredInstructionSet = instructionSet;
7730                    requirer = ps;
7731                }
7732            }
7733        }
7734
7735        if (requiredInstructionSet != null) {
7736            String adjustedAbi;
7737            if (requirer != null) {
7738                // requirer != null implies that either scannedPackage was null or that scannedPackage
7739                // did not require an ABI, in which case we have to adjust scannedPackage to match
7740                // the ABI of the set (which is the same as requirer's ABI)
7741                adjustedAbi = requirer.primaryCpuAbiString;
7742                if (scannedPackage != null) {
7743                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7744                }
7745            } else {
7746                // requirer == null implies that we're updating all ABIs in the set to
7747                // match scannedPackage.
7748                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7749            }
7750
7751            for (PackageSetting ps : packagesForUser) {
7752                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7753                    if (ps.primaryCpuAbiString != null) {
7754                        continue;
7755                    }
7756
7757                    ps.primaryCpuAbiString = adjustedAbi;
7758                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7759                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7760                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7761
7762                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7763                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7764                                bootComplete);
7765                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7766                            ps.primaryCpuAbiString = null;
7767                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7768                            return;
7769                        } else {
7770                            mInstaller.rmdex(ps.codePathString,
7771                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7772                        }
7773                    }
7774                }
7775            }
7776        }
7777    }
7778
7779    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7780        synchronized (mPackages) {
7781            mResolverReplaced = true;
7782            // Set up information for custom user intent resolution activity.
7783            mResolveActivity.applicationInfo = pkg.applicationInfo;
7784            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7785            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7786            mResolveActivity.processName = pkg.applicationInfo.packageName;
7787            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7788            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7789                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7790            mResolveActivity.theme = 0;
7791            mResolveActivity.exported = true;
7792            mResolveActivity.enabled = true;
7793            mResolveInfo.activityInfo = mResolveActivity;
7794            mResolveInfo.priority = 0;
7795            mResolveInfo.preferredOrder = 0;
7796            mResolveInfo.match = 0;
7797            mResolveComponentName = mCustomResolverComponentName;
7798            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7799                    mResolveComponentName);
7800        }
7801    }
7802
7803    private static String calculateBundledApkRoot(final String codePathString) {
7804        final File codePath = new File(codePathString);
7805        final File codeRoot;
7806        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7807            codeRoot = Environment.getRootDirectory();
7808        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7809            codeRoot = Environment.getOemDirectory();
7810        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7811            codeRoot = Environment.getVendorDirectory();
7812        } else {
7813            // Unrecognized code path; take its top real segment as the apk root:
7814            // e.g. /something/app/blah.apk => /something
7815            try {
7816                File f = codePath.getCanonicalFile();
7817                File parent = f.getParentFile();    // non-null because codePath is a file
7818                File tmp;
7819                while ((tmp = parent.getParentFile()) != null) {
7820                    f = parent;
7821                    parent = tmp;
7822                }
7823                codeRoot = f;
7824                Slog.w(TAG, "Unrecognized code path "
7825                        + codePath + " - using " + codeRoot);
7826            } catch (IOException e) {
7827                // Can't canonicalize the code path -- shenanigans?
7828                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7829                return Environment.getRootDirectory().getPath();
7830            }
7831        }
7832        return codeRoot.getPath();
7833    }
7834
7835    /**
7836     * Derive and set the location of native libraries for the given package,
7837     * which varies depending on where and how the package was installed.
7838     */
7839    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7840        final ApplicationInfo info = pkg.applicationInfo;
7841        final String codePath = pkg.codePath;
7842        final File codeFile = new File(codePath);
7843        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7844        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7845
7846        info.nativeLibraryRootDir = null;
7847        info.nativeLibraryRootRequiresIsa = false;
7848        info.nativeLibraryDir = null;
7849        info.secondaryNativeLibraryDir = null;
7850
7851        if (isApkFile(codeFile)) {
7852            // Monolithic install
7853            if (bundledApp) {
7854                // If "/system/lib64/apkname" exists, assume that is the per-package
7855                // native library directory to use; otherwise use "/system/lib/apkname".
7856                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7857                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7858                        getPrimaryInstructionSet(info));
7859
7860                // This is a bundled system app so choose the path based on the ABI.
7861                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7862                // is just the default path.
7863                final String apkName = deriveCodePathName(codePath);
7864                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7865                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7866                        apkName).getAbsolutePath();
7867
7868                if (info.secondaryCpuAbi != null) {
7869                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7870                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7871                            secondaryLibDir, apkName).getAbsolutePath();
7872                }
7873            } else if (asecApp) {
7874                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7875                        .getAbsolutePath();
7876            } else {
7877                final String apkName = deriveCodePathName(codePath);
7878                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7879                        .getAbsolutePath();
7880            }
7881
7882            info.nativeLibraryRootRequiresIsa = false;
7883            info.nativeLibraryDir = info.nativeLibraryRootDir;
7884        } else {
7885            // Cluster install
7886            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7887            info.nativeLibraryRootRequiresIsa = true;
7888
7889            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7890                    getPrimaryInstructionSet(info)).getAbsolutePath();
7891
7892            if (info.secondaryCpuAbi != null) {
7893                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7894                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7895            }
7896        }
7897    }
7898
7899    /**
7900     * Calculate the abis and roots for a bundled app. These can uniquely
7901     * be determined from the contents of the system partition, i.e whether
7902     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7903     * of this information, and instead assume that the system was built
7904     * sensibly.
7905     */
7906    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7907                                           PackageSetting pkgSetting) {
7908        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7909
7910        // If "/system/lib64/apkname" exists, assume that is the per-package
7911        // native library directory to use; otherwise use "/system/lib/apkname".
7912        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7913        setBundledAppAbi(pkg, apkRoot, apkName);
7914        // pkgSetting might be null during rescan following uninstall of updates
7915        // to a bundled app, so accommodate that possibility.  The settings in
7916        // that case will be established later from the parsed package.
7917        //
7918        // If the settings aren't null, sync them up with what we've just derived.
7919        // note that apkRoot isn't stored in the package settings.
7920        if (pkgSetting != null) {
7921            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7922            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7923        }
7924    }
7925
7926    /**
7927     * Deduces the ABI of a bundled app and sets the relevant fields on the
7928     * parsed pkg object.
7929     *
7930     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7931     *        under which system libraries are installed.
7932     * @param apkName the name of the installed package.
7933     */
7934    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7935        final File codeFile = new File(pkg.codePath);
7936
7937        final boolean has64BitLibs;
7938        final boolean has32BitLibs;
7939        if (isApkFile(codeFile)) {
7940            // Monolithic install
7941            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7942            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7943        } else {
7944            // Cluster install
7945            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7946            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7947                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7948                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7949                has64BitLibs = (new File(rootDir, isa)).exists();
7950            } else {
7951                has64BitLibs = false;
7952            }
7953            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7954                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7955                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7956                has32BitLibs = (new File(rootDir, isa)).exists();
7957            } else {
7958                has32BitLibs = false;
7959            }
7960        }
7961
7962        if (has64BitLibs && !has32BitLibs) {
7963            // The package has 64 bit libs, but not 32 bit libs. Its primary
7964            // ABI should be 64 bit. We can safely assume here that the bundled
7965            // native libraries correspond to the most preferred ABI in the list.
7966
7967            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7968            pkg.applicationInfo.secondaryCpuAbi = null;
7969        } else if (has32BitLibs && !has64BitLibs) {
7970            // The package has 32 bit libs but not 64 bit libs. Its primary
7971            // ABI should be 32 bit.
7972
7973            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7974            pkg.applicationInfo.secondaryCpuAbi = null;
7975        } else if (has32BitLibs && has64BitLibs) {
7976            // The application has both 64 and 32 bit bundled libraries. We check
7977            // here that the app declares multiArch support, and warn if it doesn't.
7978            //
7979            // We will be lenient here and record both ABIs. The primary will be the
7980            // ABI that's higher on the list, i.e, a device that's configured to prefer
7981            // 64 bit apps will see a 64 bit primary ABI,
7982
7983            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7984                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7985            }
7986
7987            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7988                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7989                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7990            } else {
7991                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7992                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7993            }
7994        } else {
7995            pkg.applicationInfo.primaryCpuAbi = null;
7996            pkg.applicationInfo.secondaryCpuAbi = null;
7997        }
7998    }
7999
8000    private void killApplication(String pkgName, int appId, String reason) {
8001        // Request the ActivityManager to kill the process(only for existing packages)
8002        // so that we do not end up in a confused state while the user is still using the older
8003        // version of the application while the new one gets installed.
8004        IActivityManager am = ActivityManagerNative.getDefault();
8005        if (am != null) {
8006            try {
8007                am.killApplicationWithAppId(pkgName, appId, reason);
8008            } catch (RemoteException e) {
8009            }
8010        }
8011    }
8012
8013    void removePackageLI(PackageSetting ps, boolean chatty) {
8014        if (DEBUG_INSTALL) {
8015            if (chatty)
8016                Log.d(TAG, "Removing package " + ps.name);
8017        }
8018
8019        // writer
8020        synchronized (mPackages) {
8021            mPackages.remove(ps.name);
8022            final PackageParser.Package pkg = ps.pkg;
8023            if (pkg != null) {
8024                cleanPackageDataStructuresLILPw(pkg, chatty);
8025            }
8026        }
8027    }
8028
8029    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8030        if (DEBUG_INSTALL) {
8031            if (chatty)
8032                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8033        }
8034
8035        // writer
8036        synchronized (mPackages) {
8037            mPackages.remove(pkg.applicationInfo.packageName);
8038            cleanPackageDataStructuresLILPw(pkg, chatty);
8039        }
8040    }
8041
8042    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8043        int N = pkg.providers.size();
8044        StringBuilder r = null;
8045        int i;
8046        for (i=0; i<N; i++) {
8047            PackageParser.Provider p = pkg.providers.get(i);
8048            mProviders.removeProvider(p);
8049            if (p.info.authority == null) {
8050
8051                /* There was another ContentProvider with this authority when
8052                 * this app was installed so this authority is null,
8053                 * Ignore it as we don't have to unregister the provider.
8054                 */
8055                continue;
8056            }
8057            String names[] = p.info.authority.split(";");
8058            for (int j = 0; j < names.length; j++) {
8059                if (mProvidersByAuthority.get(names[j]) == p) {
8060                    mProvidersByAuthority.remove(names[j]);
8061                    if (DEBUG_REMOVE) {
8062                        if (chatty)
8063                            Log.d(TAG, "Unregistered content provider: " + names[j]
8064                                    + ", className = " + p.info.name + ", isSyncable = "
8065                                    + p.info.isSyncable);
8066                    }
8067                }
8068            }
8069            if (DEBUG_REMOVE && chatty) {
8070                if (r == null) {
8071                    r = new StringBuilder(256);
8072                } else {
8073                    r.append(' ');
8074                }
8075                r.append(p.info.name);
8076            }
8077        }
8078        if (r != null) {
8079            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8080        }
8081
8082        N = pkg.services.size();
8083        r = null;
8084        for (i=0; i<N; i++) {
8085            PackageParser.Service s = pkg.services.get(i);
8086            mServices.removeService(s);
8087            if (chatty) {
8088                if (r == null) {
8089                    r = new StringBuilder(256);
8090                } else {
8091                    r.append(' ');
8092                }
8093                r.append(s.info.name);
8094            }
8095        }
8096        if (r != null) {
8097            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8098        }
8099
8100        N = pkg.receivers.size();
8101        r = null;
8102        for (i=0; i<N; i++) {
8103            PackageParser.Activity a = pkg.receivers.get(i);
8104            mReceivers.removeActivity(a, "receiver");
8105            if (DEBUG_REMOVE && chatty) {
8106                if (r == null) {
8107                    r = new StringBuilder(256);
8108                } else {
8109                    r.append(' ');
8110                }
8111                r.append(a.info.name);
8112            }
8113        }
8114        if (r != null) {
8115            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8116        }
8117
8118        N = pkg.activities.size();
8119        r = null;
8120        for (i=0; i<N; i++) {
8121            PackageParser.Activity a = pkg.activities.get(i);
8122            mActivities.removeActivity(a, "activity");
8123            if (DEBUG_REMOVE && chatty) {
8124                if (r == null) {
8125                    r = new StringBuilder(256);
8126                } else {
8127                    r.append(' ');
8128                }
8129                r.append(a.info.name);
8130            }
8131        }
8132        if (r != null) {
8133            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8134        }
8135
8136        N = pkg.permissions.size();
8137        r = null;
8138        for (i=0; i<N; i++) {
8139            PackageParser.Permission p = pkg.permissions.get(i);
8140            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8141            if (bp == null) {
8142                bp = mSettings.mPermissionTrees.get(p.info.name);
8143            }
8144            if (bp != null && bp.perm == p) {
8145                bp.perm = null;
8146                if (DEBUG_REMOVE && chatty) {
8147                    if (r == null) {
8148                        r = new StringBuilder(256);
8149                    } else {
8150                        r.append(' ');
8151                    }
8152                    r.append(p.info.name);
8153                }
8154            }
8155            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8156                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8157                if (appOpPerms != null) {
8158                    appOpPerms.remove(pkg.packageName);
8159                }
8160            }
8161        }
8162        if (r != null) {
8163            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8164        }
8165
8166        N = pkg.requestedPermissions.size();
8167        r = null;
8168        for (i=0; i<N; i++) {
8169            String perm = pkg.requestedPermissions.get(i);
8170            BasePermission bp = mSettings.mPermissions.get(perm);
8171            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8172                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8173                if (appOpPerms != null) {
8174                    appOpPerms.remove(pkg.packageName);
8175                    if (appOpPerms.isEmpty()) {
8176                        mAppOpPermissionPackages.remove(perm);
8177                    }
8178                }
8179            }
8180        }
8181        if (r != null) {
8182            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8183        }
8184
8185        N = pkg.instrumentation.size();
8186        r = null;
8187        for (i=0; i<N; i++) {
8188            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8189            mInstrumentation.remove(a.getComponentName());
8190            if (DEBUG_REMOVE && chatty) {
8191                if (r == null) {
8192                    r = new StringBuilder(256);
8193                } else {
8194                    r.append(' ');
8195                }
8196                r.append(a.info.name);
8197            }
8198        }
8199        if (r != null) {
8200            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8201        }
8202
8203        r = null;
8204        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8205            // Only system apps can hold shared libraries.
8206            if (pkg.libraryNames != null) {
8207                for (i=0; i<pkg.libraryNames.size(); i++) {
8208                    String name = pkg.libraryNames.get(i);
8209                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8210                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8211                        mSharedLibraries.remove(name);
8212                        if (DEBUG_REMOVE && chatty) {
8213                            if (r == null) {
8214                                r = new StringBuilder(256);
8215                            } else {
8216                                r.append(' ');
8217                            }
8218                            r.append(name);
8219                        }
8220                    }
8221                }
8222            }
8223        }
8224        if (r != null) {
8225            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8226        }
8227    }
8228
8229    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8230        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8231            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8232                return true;
8233            }
8234        }
8235        return false;
8236    }
8237
8238    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8239    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8240    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8241
8242    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8243            int flags) {
8244        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8245        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8246    }
8247
8248    private void updatePermissionsLPw(String changingPkg,
8249            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8250        // Make sure there are no dangling permission trees.
8251        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8252        while (it.hasNext()) {
8253            final BasePermission bp = it.next();
8254            if (bp.packageSetting == null) {
8255                // We may not yet have parsed the package, so just see if
8256                // we still know about its settings.
8257                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8258            }
8259            if (bp.packageSetting == null) {
8260                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8261                        + " from package " + bp.sourcePackage);
8262                it.remove();
8263            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8264                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8265                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8266                            + " from package " + bp.sourcePackage);
8267                    flags |= UPDATE_PERMISSIONS_ALL;
8268                    it.remove();
8269                }
8270            }
8271        }
8272
8273        // Make sure all dynamic permissions have been assigned to a package,
8274        // and make sure there are no dangling permissions.
8275        it = mSettings.mPermissions.values().iterator();
8276        while (it.hasNext()) {
8277            final BasePermission bp = it.next();
8278            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8279                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8280                        + bp.name + " pkg=" + bp.sourcePackage
8281                        + " info=" + bp.pendingInfo);
8282                if (bp.packageSetting == null && bp.pendingInfo != null) {
8283                    final BasePermission tree = findPermissionTreeLP(bp.name);
8284                    if (tree != null && tree.perm != null) {
8285                        bp.packageSetting = tree.packageSetting;
8286                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8287                                new PermissionInfo(bp.pendingInfo));
8288                        bp.perm.info.packageName = tree.perm.info.packageName;
8289                        bp.perm.info.name = bp.name;
8290                        bp.uid = tree.uid;
8291                    }
8292                }
8293            }
8294            if (bp.packageSetting == null) {
8295                // We may not yet have parsed the package, so just see if
8296                // we still know about its settings.
8297                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8298            }
8299            if (bp.packageSetting == null) {
8300                Slog.w(TAG, "Removing dangling permission: " + bp.name
8301                        + " from package " + bp.sourcePackage);
8302                it.remove();
8303            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8304                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8305                    Slog.i(TAG, "Removing old permission: " + bp.name
8306                            + " from package " + bp.sourcePackage);
8307                    flags |= UPDATE_PERMISSIONS_ALL;
8308                    it.remove();
8309                }
8310            }
8311        }
8312
8313        // Now update the permissions for all packages, in particular
8314        // replace the granted permissions of the system packages.
8315        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8316            for (PackageParser.Package pkg : mPackages.values()) {
8317                if (pkg != pkgInfo) {
8318                    // Only replace for packages on requested volume
8319                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8320                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8321                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8322                    grantPermissionsLPw(pkg, replace, changingPkg);
8323                }
8324            }
8325        }
8326
8327        if (pkgInfo != null) {
8328            // Only replace for packages on requested volume
8329            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8330            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8331                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8332            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8333        }
8334    }
8335
8336    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8337            String packageOfInterest) {
8338        // IMPORTANT: There are two types of permissions: install and runtime.
8339        // Install time permissions are granted when the app is installed to
8340        // all device users and users added in the future. Runtime permissions
8341        // are granted at runtime explicitly to specific users. Normal and signature
8342        // protected permissions are install time permissions. Dangerous permissions
8343        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8344        // otherwise they are runtime permissions. This function does not manage
8345        // runtime permissions except for the case an app targeting Lollipop MR1
8346        // being upgraded to target a newer SDK, in which case dangerous permissions
8347        // are transformed from install time to runtime ones.
8348
8349        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8350        if (ps == null) {
8351            return;
8352        }
8353
8354        PermissionsState permissionsState = ps.getPermissionsState();
8355        PermissionsState origPermissions = permissionsState;
8356
8357        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8358
8359        boolean runtimePermissionsRevoked = false;
8360        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8361
8362        boolean changedInstallPermission = false;
8363
8364        if (replace) {
8365            ps.installPermissionsFixed = false;
8366            if (!ps.isSharedUser()) {
8367                origPermissions = new PermissionsState(permissionsState);
8368                permissionsState.reset();
8369            } else {
8370                // We need to know only about runtime permission changes since the
8371                // calling code always writes the install permissions state but
8372                // the runtime ones are written only if changed. The only cases of
8373                // changed runtime permissions here are promotion of an install to
8374                // runtime and revocation of a runtime from a shared user.
8375                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8376                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8377                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8378                    runtimePermissionsRevoked = true;
8379                }
8380            }
8381        }
8382
8383        permissionsState.setGlobalGids(mGlobalGids);
8384
8385        final int N = pkg.requestedPermissions.size();
8386        for (int i=0; i<N; i++) {
8387            final String name = pkg.requestedPermissions.get(i);
8388            final BasePermission bp = mSettings.mPermissions.get(name);
8389
8390            if (DEBUG_INSTALL) {
8391                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8392            }
8393
8394            if (bp == null || bp.packageSetting == null) {
8395                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8396                    Slog.w(TAG, "Unknown permission " + name
8397                            + " in package " + pkg.packageName);
8398                }
8399                continue;
8400            }
8401
8402            final String perm = bp.name;
8403            boolean allowedSig = false;
8404            int grant = GRANT_DENIED;
8405
8406            // Keep track of app op permissions.
8407            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8408                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8409                if (pkgs == null) {
8410                    pkgs = new ArraySet<>();
8411                    mAppOpPermissionPackages.put(bp.name, pkgs);
8412                }
8413                pkgs.add(pkg.packageName);
8414            }
8415
8416            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8417            switch (level) {
8418                case PermissionInfo.PROTECTION_NORMAL: {
8419                    // For all apps normal permissions are install time ones.
8420                    grant = GRANT_INSTALL;
8421                } break;
8422
8423                case PermissionInfo.PROTECTION_DANGEROUS: {
8424                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8425                        // For legacy apps dangerous permissions are install time ones.
8426                        grant = GRANT_INSTALL_LEGACY;
8427                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8428                        // For legacy apps that became modern, install becomes runtime.
8429                        grant = GRANT_UPGRADE;
8430                    } else if (mPromoteSystemApps
8431                            && isSystemApp(ps)
8432                            && mExistingSystemPackages.contains(ps.name)) {
8433                        // For legacy system apps, install becomes runtime.
8434                        // We cannot check hasInstallPermission() for system apps since those
8435                        // permissions were granted implicitly and not persisted pre-M.
8436                        grant = GRANT_UPGRADE;
8437                    } else {
8438                        // For modern apps keep runtime permissions unchanged.
8439                        grant = GRANT_RUNTIME;
8440                    }
8441                } break;
8442
8443                case PermissionInfo.PROTECTION_SIGNATURE: {
8444                    // For all apps signature permissions are install time ones.
8445                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8446                    if (allowedSig) {
8447                        grant = GRANT_INSTALL;
8448                    }
8449                } break;
8450            }
8451
8452            if (DEBUG_INSTALL) {
8453                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8454            }
8455
8456            if (grant != GRANT_DENIED) {
8457                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8458                    // If this is an existing, non-system package, then
8459                    // we can't add any new permissions to it.
8460                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8461                        // Except...  if this is a permission that was added
8462                        // to the platform (note: need to only do this when
8463                        // updating the platform).
8464                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8465                            grant = GRANT_DENIED;
8466                        }
8467                    }
8468                }
8469
8470                switch (grant) {
8471                    case GRANT_INSTALL: {
8472                        // Revoke this as runtime permission to handle the case of
8473                        // a runtime permission being downgraded to an install one.
8474                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8475                            if (origPermissions.getRuntimePermissionState(
8476                                    bp.name, userId) != null) {
8477                                // Revoke the runtime permission and clear the flags.
8478                                origPermissions.revokeRuntimePermission(bp, userId);
8479                                origPermissions.updatePermissionFlags(bp, userId,
8480                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8481                                // If we revoked a permission permission, we have to write.
8482                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8483                                        changedRuntimePermissionUserIds, userId);
8484                            }
8485                        }
8486                        // Grant an install permission.
8487                        if (permissionsState.grantInstallPermission(bp) !=
8488                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8489                            changedInstallPermission = true;
8490                        }
8491                    } break;
8492
8493                    case GRANT_INSTALL_LEGACY: {
8494                        // Grant an install permission.
8495                        if (permissionsState.grantInstallPermission(bp) !=
8496                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8497                            changedInstallPermission = true;
8498                        }
8499                    } break;
8500
8501                    case GRANT_RUNTIME: {
8502                        // Grant previously granted runtime permissions.
8503                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8504                            PermissionState permissionState = origPermissions
8505                                    .getRuntimePermissionState(bp.name, userId);
8506                            final int flags = permissionState != null
8507                                    ? permissionState.getFlags() : 0;
8508                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8509                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8510                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8511                                    // If we cannot put the permission as it was, we have to write.
8512                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8513                                            changedRuntimePermissionUserIds, userId);
8514                                }
8515                            }
8516                            // Propagate the permission flags.
8517                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8518                        }
8519                    } break;
8520
8521                    case GRANT_UPGRADE: {
8522                        // Grant runtime permissions for a previously held install permission.
8523                        PermissionState permissionState = origPermissions
8524                                .getInstallPermissionState(bp.name);
8525                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8526
8527                        if (origPermissions.revokeInstallPermission(bp)
8528                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8529                            // We will be transferring the permission flags, so clear them.
8530                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8531                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8532                            changedInstallPermission = true;
8533                        }
8534
8535                        // If the permission is not to be promoted to runtime we ignore it and
8536                        // also its other flags as they are not applicable to install permissions.
8537                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8538                            for (int userId : currentUserIds) {
8539                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8540                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8541                                    // Transfer the permission flags.
8542                                    permissionsState.updatePermissionFlags(bp, userId,
8543                                            flags, flags);
8544                                    // If we granted the permission, we have to write.
8545                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8546                                            changedRuntimePermissionUserIds, userId);
8547                                }
8548                            }
8549                        }
8550                    } break;
8551
8552                    default: {
8553                        if (packageOfInterest == null
8554                                || packageOfInterest.equals(pkg.packageName)) {
8555                            Slog.w(TAG, "Not granting permission " + perm
8556                                    + " to package " + pkg.packageName
8557                                    + " because it was previously installed without");
8558                        }
8559                    } break;
8560                }
8561            } else {
8562                if (permissionsState.revokeInstallPermission(bp) !=
8563                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8564                    // Also drop the permission flags.
8565                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8566                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8567                    changedInstallPermission = true;
8568                    Slog.i(TAG, "Un-granting permission " + perm
8569                            + " from package " + pkg.packageName
8570                            + " (protectionLevel=" + bp.protectionLevel
8571                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8572                            + ")");
8573                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8574                    // Don't print warning for app op permissions, since it is fine for them
8575                    // not to be granted, there is a UI for the user to decide.
8576                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8577                        Slog.w(TAG, "Not granting permission " + perm
8578                                + " to package " + pkg.packageName
8579                                + " (protectionLevel=" + bp.protectionLevel
8580                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8581                                + ")");
8582                    }
8583                }
8584            }
8585        }
8586
8587        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8588                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8589            // This is the first that we have heard about this package, so the
8590            // permissions we have now selected are fixed until explicitly
8591            // changed.
8592            ps.installPermissionsFixed = true;
8593        }
8594
8595        // Persist the runtime permissions state for users with changes. If permissions
8596        // were revoked because no app in the shared user declares them we have to
8597        // write synchronously to avoid losing runtime permissions state.
8598        for (int userId : changedRuntimePermissionUserIds) {
8599            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8600        }
8601    }
8602
8603    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8604        boolean allowed = false;
8605        final int NP = PackageParser.NEW_PERMISSIONS.length;
8606        for (int ip=0; ip<NP; ip++) {
8607            final PackageParser.NewPermissionInfo npi
8608                    = PackageParser.NEW_PERMISSIONS[ip];
8609            if (npi.name.equals(perm)
8610                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8611                allowed = true;
8612                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8613                        + pkg.packageName);
8614                break;
8615            }
8616        }
8617        return allowed;
8618    }
8619
8620    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8621            BasePermission bp, PermissionsState origPermissions) {
8622        boolean allowed;
8623        allowed = (compareSignatures(
8624                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8625                        == PackageManager.SIGNATURE_MATCH)
8626                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8627                        == PackageManager.SIGNATURE_MATCH);
8628        if (!allowed && (bp.protectionLevel
8629                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8630            if (isSystemApp(pkg)) {
8631                // For updated system applications, a system permission
8632                // is granted only if it had been defined by the original application.
8633                if (pkg.isUpdatedSystemApp()) {
8634                    final PackageSetting sysPs = mSettings
8635                            .getDisabledSystemPkgLPr(pkg.packageName);
8636                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8637                        // If the original was granted this permission, we take
8638                        // that grant decision as read and propagate it to the
8639                        // update.
8640                        if (sysPs.isPrivileged()) {
8641                            allowed = true;
8642                        }
8643                    } else {
8644                        // The system apk may have been updated with an older
8645                        // version of the one on the data partition, but which
8646                        // granted a new system permission that it didn't have
8647                        // before.  In this case we do want to allow the app to
8648                        // now get the new permission if the ancestral apk is
8649                        // privileged to get it.
8650                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8651                            for (int j=0;
8652                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8653                                if (perm.equals(
8654                                        sysPs.pkg.requestedPermissions.get(j))) {
8655                                    allowed = true;
8656                                    break;
8657                                }
8658                            }
8659                        }
8660                    }
8661                } else {
8662                    allowed = isPrivilegedApp(pkg);
8663                }
8664            }
8665        }
8666        if (!allowed) {
8667            if (!allowed && (bp.protectionLevel
8668                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8669                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8670                // If this was a previously normal/dangerous permission that got moved
8671                // to a system permission as part of the runtime permission redesign, then
8672                // we still want to blindly grant it to old apps.
8673                allowed = true;
8674            }
8675            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8676                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8677                // If this permission is to be granted to the system installer and
8678                // this app is an installer, then it gets the permission.
8679                allowed = true;
8680            }
8681            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8682                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8683                // If this permission is to be granted to the system verifier and
8684                // this app is a verifier, then it gets the permission.
8685                allowed = true;
8686            }
8687            if (!allowed && (bp.protectionLevel
8688                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8689                    && isSystemApp(pkg)) {
8690                // Any pre-installed system app is allowed to get this permission.
8691                allowed = true;
8692            }
8693            if (!allowed && (bp.protectionLevel
8694                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8695                // For development permissions, a development permission
8696                // is granted only if it was already granted.
8697                allowed = origPermissions.hasInstallPermission(perm);
8698            }
8699        }
8700        return allowed;
8701    }
8702
8703    final class ActivityIntentResolver
8704            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8705        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8706                boolean defaultOnly, int userId) {
8707            if (!sUserManager.exists(userId)) return null;
8708            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8709            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8710        }
8711
8712        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8713                int userId) {
8714            if (!sUserManager.exists(userId)) return null;
8715            mFlags = flags;
8716            return super.queryIntent(intent, resolvedType,
8717                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8718        }
8719
8720        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8721                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8722            if (!sUserManager.exists(userId)) return null;
8723            if (packageActivities == null) {
8724                return null;
8725            }
8726            mFlags = flags;
8727            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8728            final int N = packageActivities.size();
8729            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8730                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8731
8732            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8733            for (int i = 0; i < N; ++i) {
8734                intentFilters = packageActivities.get(i).intents;
8735                if (intentFilters != null && intentFilters.size() > 0) {
8736                    PackageParser.ActivityIntentInfo[] array =
8737                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8738                    intentFilters.toArray(array);
8739                    listCut.add(array);
8740                }
8741            }
8742            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8743        }
8744
8745        public final void addActivity(PackageParser.Activity a, String type) {
8746            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8747            mActivities.put(a.getComponentName(), a);
8748            if (DEBUG_SHOW_INFO)
8749                Log.v(
8750                TAG, "  " + type + " " +
8751                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8752            if (DEBUG_SHOW_INFO)
8753                Log.v(TAG, "    Class=" + a.info.name);
8754            final int NI = a.intents.size();
8755            for (int j=0; j<NI; j++) {
8756                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8757                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8758                    intent.setPriority(0);
8759                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8760                            + a.className + " with priority > 0, forcing to 0");
8761                }
8762                if (DEBUG_SHOW_INFO) {
8763                    Log.v(TAG, "    IntentFilter:");
8764                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8765                }
8766                if (!intent.debugCheck()) {
8767                    Log.w(TAG, "==> For Activity " + a.info.name);
8768                }
8769                addFilter(intent);
8770            }
8771        }
8772
8773        public final void removeActivity(PackageParser.Activity a, String type) {
8774            mActivities.remove(a.getComponentName());
8775            if (DEBUG_SHOW_INFO) {
8776                Log.v(TAG, "  " + type + " "
8777                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8778                                : a.info.name) + ":");
8779                Log.v(TAG, "    Class=" + a.info.name);
8780            }
8781            final int NI = a.intents.size();
8782            for (int j=0; j<NI; j++) {
8783                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8784                if (DEBUG_SHOW_INFO) {
8785                    Log.v(TAG, "    IntentFilter:");
8786                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8787                }
8788                removeFilter(intent);
8789            }
8790        }
8791
8792        @Override
8793        protected boolean allowFilterResult(
8794                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8795            ActivityInfo filterAi = filter.activity.info;
8796            for (int i=dest.size()-1; i>=0; i--) {
8797                ActivityInfo destAi = dest.get(i).activityInfo;
8798                if (destAi.name == filterAi.name
8799                        && destAi.packageName == filterAi.packageName) {
8800                    return false;
8801                }
8802            }
8803            return true;
8804        }
8805
8806        @Override
8807        protected ActivityIntentInfo[] newArray(int size) {
8808            return new ActivityIntentInfo[size];
8809        }
8810
8811        @Override
8812        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8813            if (!sUserManager.exists(userId)) return true;
8814            PackageParser.Package p = filter.activity.owner;
8815            if (p != null) {
8816                PackageSetting ps = (PackageSetting)p.mExtras;
8817                if (ps != null) {
8818                    // System apps are never considered stopped for purposes of
8819                    // filtering, because there may be no way for the user to
8820                    // actually re-launch them.
8821                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8822                            && ps.getStopped(userId);
8823                }
8824            }
8825            return false;
8826        }
8827
8828        @Override
8829        protected boolean isPackageForFilter(String packageName,
8830                PackageParser.ActivityIntentInfo info) {
8831            return packageName.equals(info.activity.owner.packageName);
8832        }
8833
8834        @Override
8835        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8836                int match, int userId) {
8837            if (!sUserManager.exists(userId)) return null;
8838            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8839                return null;
8840            }
8841            final PackageParser.Activity activity = info.activity;
8842            if (mSafeMode && (activity.info.applicationInfo.flags
8843                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8844                return null;
8845            }
8846            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8847            if (ps == null) {
8848                return null;
8849            }
8850            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8851                    ps.readUserState(userId), userId);
8852            if (ai == null) {
8853                return null;
8854            }
8855            final ResolveInfo res = new ResolveInfo();
8856            res.activityInfo = ai;
8857            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8858                res.filter = info;
8859            }
8860            if (info != null) {
8861                res.handleAllWebDataURI = info.handleAllWebDataURI();
8862            }
8863            res.priority = info.getPriority();
8864            res.preferredOrder = activity.owner.mPreferredOrder;
8865            //System.out.println("Result: " + res.activityInfo.className +
8866            //                   " = " + res.priority);
8867            res.match = match;
8868            res.isDefault = info.hasDefault;
8869            res.labelRes = info.labelRes;
8870            res.nonLocalizedLabel = info.nonLocalizedLabel;
8871            if (userNeedsBadging(userId)) {
8872                res.noResourceId = true;
8873            } else {
8874                res.icon = info.icon;
8875            }
8876            res.iconResourceId = info.icon;
8877            res.system = res.activityInfo.applicationInfo.isSystemApp();
8878            return res;
8879        }
8880
8881        @Override
8882        protected void sortResults(List<ResolveInfo> results) {
8883            Collections.sort(results, mResolvePrioritySorter);
8884        }
8885
8886        @Override
8887        protected void dumpFilter(PrintWriter out, String prefix,
8888                PackageParser.ActivityIntentInfo filter) {
8889            out.print(prefix); out.print(
8890                    Integer.toHexString(System.identityHashCode(filter.activity)));
8891                    out.print(' ');
8892                    filter.activity.printComponentShortName(out);
8893                    out.print(" filter ");
8894                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8895        }
8896
8897        @Override
8898        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8899            return filter.activity;
8900        }
8901
8902        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8903            PackageParser.Activity activity = (PackageParser.Activity)label;
8904            out.print(prefix); out.print(
8905                    Integer.toHexString(System.identityHashCode(activity)));
8906                    out.print(' ');
8907                    activity.printComponentShortName(out);
8908            if (count > 1) {
8909                out.print(" ("); out.print(count); out.print(" filters)");
8910            }
8911            out.println();
8912        }
8913
8914//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8915//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8916//            final List<ResolveInfo> retList = Lists.newArrayList();
8917//            while (i.hasNext()) {
8918//                final ResolveInfo resolveInfo = i.next();
8919//                if (isEnabledLP(resolveInfo.activityInfo)) {
8920//                    retList.add(resolveInfo);
8921//                }
8922//            }
8923//            return retList;
8924//        }
8925
8926        // Keys are String (activity class name), values are Activity.
8927        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8928                = new ArrayMap<ComponentName, PackageParser.Activity>();
8929        private int mFlags;
8930    }
8931
8932    private final class ServiceIntentResolver
8933            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8935                boolean defaultOnly, int userId) {
8936            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8937            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8938        }
8939
8940        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8941                int userId) {
8942            if (!sUserManager.exists(userId)) return null;
8943            mFlags = flags;
8944            return super.queryIntent(intent, resolvedType,
8945                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8946        }
8947
8948        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8949                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8950            if (!sUserManager.exists(userId)) return null;
8951            if (packageServices == null) {
8952                return null;
8953            }
8954            mFlags = flags;
8955            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8956            final int N = packageServices.size();
8957            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8958                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8959
8960            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8961            for (int i = 0; i < N; ++i) {
8962                intentFilters = packageServices.get(i).intents;
8963                if (intentFilters != null && intentFilters.size() > 0) {
8964                    PackageParser.ServiceIntentInfo[] array =
8965                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8966                    intentFilters.toArray(array);
8967                    listCut.add(array);
8968                }
8969            }
8970            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8971        }
8972
8973        public final void addService(PackageParser.Service s) {
8974            mServices.put(s.getComponentName(), s);
8975            if (DEBUG_SHOW_INFO) {
8976                Log.v(TAG, "  "
8977                        + (s.info.nonLocalizedLabel != null
8978                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8979                Log.v(TAG, "    Class=" + s.info.name);
8980            }
8981            final int NI = s.intents.size();
8982            int j;
8983            for (j=0; j<NI; j++) {
8984                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8985                if (DEBUG_SHOW_INFO) {
8986                    Log.v(TAG, "    IntentFilter:");
8987                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8988                }
8989                if (!intent.debugCheck()) {
8990                    Log.w(TAG, "==> For Service " + s.info.name);
8991                }
8992                addFilter(intent);
8993            }
8994        }
8995
8996        public final void removeService(PackageParser.Service s) {
8997            mServices.remove(s.getComponentName());
8998            if (DEBUG_SHOW_INFO) {
8999                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9000                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9001                Log.v(TAG, "    Class=" + s.info.name);
9002            }
9003            final int NI = s.intents.size();
9004            int j;
9005            for (j=0; j<NI; j++) {
9006                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9007                if (DEBUG_SHOW_INFO) {
9008                    Log.v(TAG, "    IntentFilter:");
9009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9010                }
9011                removeFilter(intent);
9012            }
9013        }
9014
9015        @Override
9016        protected boolean allowFilterResult(
9017                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9018            ServiceInfo filterSi = filter.service.info;
9019            for (int i=dest.size()-1; i>=0; i--) {
9020                ServiceInfo destAi = dest.get(i).serviceInfo;
9021                if (destAi.name == filterSi.name
9022                        && destAi.packageName == filterSi.packageName) {
9023                    return false;
9024                }
9025            }
9026            return true;
9027        }
9028
9029        @Override
9030        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9031            return new PackageParser.ServiceIntentInfo[size];
9032        }
9033
9034        @Override
9035        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9036            if (!sUserManager.exists(userId)) return true;
9037            PackageParser.Package p = filter.service.owner;
9038            if (p != null) {
9039                PackageSetting ps = (PackageSetting)p.mExtras;
9040                if (ps != null) {
9041                    // System apps are never considered stopped for purposes of
9042                    // filtering, because there may be no way for the user to
9043                    // actually re-launch them.
9044                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9045                            && ps.getStopped(userId);
9046                }
9047            }
9048            return false;
9049        }
9050
9051        @Override
9052        protected boolean isPackageForFilter(String packageName,
9053                PackageParser.ServiceIntentInfo info) {
9054            return packageName.equals(info.service.owner.packageName);
9055        }
9056
9057        @Override
9058        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9059                int match, int userId) {
9060            if (!sUserManager.exists(userId)) return null;
9061            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9062            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9063                return null;
9064            }
9065            final PackageParser.Service service = info.service;
9066            if (mSafeMode && (service.info.applicationInfo.flags
9067                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9068                return null;
9069            }
9070            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9071            if (ps == null) {
9072                return null;
9073            }
9074            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9075                    ps.readUserState(userId), userId);
9076            if (si == null) {
9077                return null;
9078            }
9079            final ResolveInfo res = new ResolveInfo();
9080            res.serviceInfo = si;
9081            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9082                res.filter = filter;
9083            }
9084            res.priority = info.getPriority();
9085            res.preferredOrder = service.owner.mPreferredOrder;
9086            res.match = match;
9087            res.isDefault = info.hasDefault;
9088            res.labelRes = info.labelRes;
9089            res.nonLocalizedLabel = info.nonLocalizedLabel;
9090            res.icon = info.icon;
9091            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9092            return res;
9093        }
9094
9095        @Override
9096        protected void sortResults(List<ResolveInfo> results) {
9097            Collections.sort(results, mResolvePrioritySorter);
9098        }
9099
9100        @Override
9101        protected void dumpFilter(PrintWriter out, String prefix,
9102                PackageParser.ServiceIntentInfo filter) {
9103            out.print(prefix); out.print(
9104                    Integer.toHexString(System.identityHashCode(filter.service)));
9105                    out.print(' ');
9106                    filter.service.printComponentShortName(out);
9107                    out.print(" filter ");
9108                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9109        }
9110
9111        @Override
9112        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9113            return filter.service;
9114        }
9115
9116        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9117            PackageParser.Service service = (PackageParser.Service)label;
9118            out.print(prefix); out.print(
9119                    Integer.toHexString(System.identityHashCode(service)));
9120                    out.print(' ');
9121                    service.printComponentShortName(out);
9122            if (count > 1) {
9123                out.print(" ("); out.print(count); out.print(" filters)");
9124            }
9125            out.println();
9126        }
9127
9128//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9129//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9130//            final List<ResolveInfo> retList = Lists.newArrayList();
9131//            while (i.hasNext()) {
9132//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9133//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9134//                    retList.add(resolveInfo);
9135//                }
9136//            }
9137//            return retList;
9138//        }
9139
9140        // Keys are String (activity class name), values are Activity.
9141        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9142                = new ArrayMap<ComponentName, PackageParser.Service>();
9143        private int mFlags;
9144    };
9145
9146    private final class ProviderIntentResolver
9147            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9148        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9149                boolean defaultOnly, int userId) {
9150            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9151            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9152        }
9153
9154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9155                int userId) {
9156            if (!sUserManager.exists(userId))
9157                return null;
9158            mFlags = flags;
9159            return super.queryIntent(intent, resolvedType,
9160                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9161        }
9162
9163        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9164                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9165            if (!sUserManager.exists(userId))
9166                return null;
9167            if (packageProviders == null) {
9168                return null;
9169            }
9170            mFlags = flags;
9171            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9172            final int N = packageProviders.size();
9173            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9174                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9175
9176            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9177            for (int i = 0; i < N; ++i) {
9178                intentFilters = packageProviders.get(i).intents;
9179                if (intentFilters != null && intentFilters.size() > 0) {
9180                    PackageParser.ProviderIntentInfo[] array =
9181                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9182                    intentFilters.toArray(array);
9183                    listCut.add(array);
9184                }
9185            }
9186            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9187        }
9188
9189        public final void addProvider(PackageParser.Provider p) {
9190            if (mProviders.containsKey(p.getComponentName())) {
9191                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9192                return;
9193            }
9194
9195            mProviders.put(p.getComponentName(), p);
9196            if (DEBUG_SHOW_INFO) {
9197                Log.v(TAG, "  "
9198                        + (p.info.nonLocalizedLabel != null
9199                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9200                Log.v(TAG, "    Class=" + p.info.name);
9201            }
9202            final int NI = p.intents.size();
9203            int j;
9204            for (j = 0; j < NI; j++) {
9205                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9206                if (DEBUG_SHOW_INFO) {
9207                    Log.v(TAG, "    IntentFilter:");
9208                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9209                }
9210                if (!intent.debugCheck()) {
9211                    Log.w(TAG, "==> For Provider " + p.info.name);
9212                }
9213                addFilter(intent);
9214            }
9215        }
9216
9217        public final void removeProvider(PackageParser.Provider p) {
9218            mProviders.remove(p.getComponentName());
9219            if (DEBUG_SHOW_INFO) {
9220                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9221                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9222                Log.v(TAG, "    Class=" + p.info.name);
9223            }
9224            final int NI = p.intents.size();
9225            int j;
9226            for (j = 0; j < NI; j++) {
9227                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9228                if (DEBUG_SHOW_INFO) {
9229                    Log.v(TAG, "    IntentFilter:");
9230                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9231                }
9232                removeFilter(intent);
9233            }
9234        }
9235
9236        @Override
9237        protected boolean allowFilterResult(
9238                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9239            ProviderInfo filterPi = filter.provider.info;
9240            for (int i = dest.size() - 1; i >= 0; i--) {
9241                ProviderInfo destPi = dest.get(i).providerInfo;
9242                if (destPi.name == filterPi.name
9243                        && destPi.packageName == filterPi.packageName) {
9244                    return false;
9245                }
9246            }
9247            return true;
9248        }
9249
9250        @Override
9251        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9252            return new PackageParser.ProviderIntentInfo[size];
9253        }
9254
9255        @Override
9256        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9257            if (!sUserManager.exists(userId))
9258                return true;
9259            PackageParser.Package p = filter.provider.owner;
9260            if (p != null) {
9261                PackageSetting ps = (PackageSetting) p.mExtras;
9262                if (ps != null) {
9263                    // System apps are never considered stopped for purposes of
9264                    // filtering, because there may be no way for the user to
9265                    // actually re-launch them.
9266                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9267                            && ps.getStopped(userId);
9268                }
9269            }
9270            return false;
9271        }
9272
9273        @Override
9274        protected boolean isPackageForFilter(String packageName,
9275                PackageParser.ProviderIntentInfo info) {
9276            return packageName.equals(info.provider.owner.packageName);
9277        }
9278
9279        @Override
9280        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9281                int match, int userId) {
9282            if (!sUserManager.exists(userId))
9283                return null;
9284            final PackageParser.ProviderIntentInfo info = filter;
9285            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9286                return null;
9287            }
9288            final PackageParser.Provider provider = info.provider;
9289            if (mSafeMode && (provider.info.applicationInfo.flags
9290                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9291                return null;
9292            }
9293            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9294            if (ps == null) {
9295                return null;
9296            }
9297            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9298                    ps.readUserState(userId), userId);
9299            if (pi == null) {
9300                return null;
9301            }
9302            final ResolveInfo res = new ResolveInfo();
9303            res.providerInfo = pi;
9304            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9305                res.filter = filter;
9306            }
9307            res.priority = info.getPriority();
9308            res.preferredOrder = provider.owner.mPreferredOrder;
9309            res.match = match;
9310            res.isDefault = info.hasDefault;
9311            res.labelRes = info.labelRes;
9312            res.nonLocalizedLabel = info.nonLocalizedLabel;
9313            res.icon = info.icon;
9314            res.system = res.providerInfo.applicationInfo.isSystemApp();
9315            return res;
9316        }
9317
9318        @Override
9319        protected void sortResults(List<ResolveInfo> results) {
9320            Collections.sort(results, mResolvePrioritySorter);
9321        }
9322
9323        @Override
9324        protected void dumpFilter(PrintWriter out, String prefix,
9325                PackageParser.ProviderIntentInfo filter) {
9326            out.print(prefix);
9327            out.print(
9328                    Integer.toHexString(System.identityHashCode(filter.provider)));
9329            out.print(' ');
9330            filter.provider.printComponentShortName(out);
9331            out.print(" filter ");
9332            out.println(Integer.toHexString(System.identityHashCode(filter)));
9333        }
9334
9335        @Override
9336        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9337            return filter.provider;
9338        }
9339
9340        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9341            PackageParser.Provider provider = (PackageParser.Provider)label;
9342            out.print(prefix); out.print(
9343                    Integer.toHexString(System.identityHashCode(provider)));
9344                    out.print(' ');
9345                    provider.printComponentShortName(out);
9346            if (count > 1) {
9347                out.print(" ("); out.print(count); out.print(" filters)");
9348            }
9349            out.println();
9350        }
9351
9352        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9353                = new ArrayMap<ComponentName, PackageParser.Provider>();
9354        private int mFlags;
9355    };
9356
9357    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9358            new Comparator<ResolveInfo>() {
9359        public int compare(ResolveInfo r1, ResolveInfo r2) {
9360            int v1 = r1.priority;
9361            int v2 = r2.priority;
9362            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9363            if (v1 != v2) {
9364                return (v1 > v2) ? -1 : 1;
9365            }
9366            v1 = r1.preferredOrder;
9367            v2 = r2.preferredOrder;
9368            if (v1 != v2) {
9369                return (v1 > v2) ? -1 : 1;
9370            }
9371            if (r1.isDefault != r2.isDefault) {
9372                return r1.isDefault ? -1 : 1;
9373            }
9374            v1 = r1.match;
9375            v2 = r2.match;
9376            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9377            if (v1 != v2) {
9378                return (v1 > v2) ? -1 : 1;
9379            }
9380            if (r1.system != r2.system) {
9381                return r1.system ? -1 : 1;
9382            }
9383            return 0;
9384        }
9385    };
9386
9387    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9388            new Comparator<ProviderInfo>() {
9389        public int compare(ProviderInfo p1, ProviderInfo p2) {
9390            final int v1 = p1.initOrder;
9391            final int v2 = p2.initOrder;
9392            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9393        }
9394    };
9395
9396    final void sendPackageBroadcast(final String action, final String pkg,
9397            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9398            final int[] userIds) {
9399        mHandler.post(new Runnable() {
9400            @Override
9401            public void run() {
9402                try {
9403                    final IActivityManager am = ActivityManagerNative.getDefault();
9404                    if (am == null) return;
9405                    final int[] resolvedUserIds;
9406                    if (userIds == null) {
9407                        resolvedUserIds = am.getRunningUserIds();
9408                    } else {
9409                        resolvedUserIds = userIds;
9410                    }
9411                    for (int id : resolvedUserIds) {
9412                        final Intent intent = new Intent(action,
9413                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9414                        if (extras != null) {
9415                            intent.putExtras(extras);
9416                        }
9417                        if (targetPkg != null) {
9418                            intent.setPackage(targetPkg);
9419                        }
9420                        // Modify the UID when posting to other users
9421                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9422                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9423                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9424                            intent.putExtra(Intent.EXTRA_UID, uid);
9425                        }
9426                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9427                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9428                        if (DEBUG_BROADCASTS) {
9429                            RuntimeException here = new RuntimeException("here");
9430                            here.fillInStackTrace();
9431                            Slog.d(TAG, "Sending to user " + id + ": "
9432                                    + intent.toShortString(false, true, false, false)
9433                                    + " " + intent.getExtras(), here);
9434                        }
9435                        am.broadcastIntent(null, intent, null, finishedReceiver,
9436                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9437                                null, finishedReceiver != null, false, id);
9438                    }
9439                } catch (RemoteException ex) {
9440                }
9441            }
9442        });
9443    }
9444
9445    /**
9446     * Check if the external storage media is available. This is true if there
9447     * is a mounted external storage medium or if the external storage is
9448     * emulated.
9449     */
9450    private boolean isExternalMediaAvailable() {
9451        return mMediaMounted || Environment.isExternalStorageEmulated();
9452    }
9453
9454    @Override
9455    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9456        // writer
9457        synchronized (mPackages) {
9458            if (!isExternalMediaAvailable()) {
9459                // If the external storage is no longer mounted at this point,
9460                // the caller may not have been able to delete all of this
9461                // packages files and can not delete any more.  Bail.
9462                return null;
9463            }
9464            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9465            if (lastPackage != null) {
9466                pkgs.remove(lastPackage);
9467            }
9468            if (pkgs.size() > 0) {
9469                return pkgs.get(0);
9470            }
9471        }
9472        return null;
9473    }
9474
9475    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9476        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9477                userId, andCode ? 1 : 0, packageName);
9478        if (mSystemReady) {
9479            msg.sendToTarget();
9480        } else {
9481            if (mPostSystemReadyMessages == null) {
9482                mPostSystemReadyMessages = new ArrayList<>();
9483            }
9484            mPostSystemReadyMessages.add(msg);
9485        }
9486    }
9487
9488    void startCleaningPackages() {
9489        // reader
9490        synchronized (mPackages) {
9491            if (!isExternalMediaAvailable()) {
9492                return;
9493            }
9494            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9495                return;
9496            }
9497        }
9498        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9499        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9500        IActivityManager am = ActivityManagerNative.getDefault();
9501        if (am != null) {
9502            try {
9503                am.startService(null, intent, null, mContext.getOpPackageName(),
9504                        UserHandle.USER_OWNER);
9505            } catch (RemoteException e) {
9506            }
9507        }
9508    }
9509
9510    @Override
9511    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9512            int installFlags, String installerPackageName, VerificationParams verificationParams,
9513            String packageAbiOverride) {
9514        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9515                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9516    }
9517
9518    @Override
9519    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9520            int installFlags, String installerPackageName, VerificationParams verificationParams,
9521            String packageAbiOverride, int userId) {
9522        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9523
9524        final int callingUid = Binder.getCallingUid();
9525        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9526
9527        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9528            try {
9529                if (observer != null) {
9530                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9531                }
9532            } catch (RemoteException re) {
9533            }
9534            return;
9535        }
9536
9537        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9538            installFlags |= PackageManager.INSTALL_FROM_ADB;
9539
9540        } else {
9541            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9542            // about installerPackageName.
9543
9544            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9545            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9546        }
9547
9548        UserHandle user;
9549        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9550            user = UserHandle.ALL;
9551        } else {
9552            user = new UserHandle(userId);
9553        }
9554
9555        // Only system components can circumvent runtime permissions when installing.
9556        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9557                && mContext.checkCallingOrSelfPermission(Manifest.permission
9558                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9559            throw new SecurityException("You need the "
9560                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9561                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9562        }
9563
9564        verificationParams.setInstallerUid(callingUid);
9565
9566        final File originFile = new File(originPath);
9567        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9568
9569        final Message msg = mHandler.obtainMessage(INIT_COPY);
9570        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9571                null, verificationParams, user, packageAbiOverride, null);
9572        mHandler.sendMessage(msg);
9573    }
9574
9575    void installStage(String packageName, File stagedDir, String stagedCid,
9576            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9577            String installerPackageName, int installerUid, UserHandle user) {
9578        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9579                params.referrerUri, installerUid, null);
9580        verifParams.setInstallerUid(installerUid);
9581
9582        final OriginInfo origin;
9583        if (stagedDir != null) {
9584            origin = OriginInfo.fromStagedFile(stagedDir);
9585        } else {
9586            origin = OriginInfo.fromStagedContainer(stagedCid);
9587        }
9588
9589        final Message msg = mHandler.obtainMessage(INIT_COPY);
9590        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9591                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9592                params.grantedRuntimePermissions);
9593        mHandler.sendMessage(msg);
9594    }
9595
9596    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9597        Bundle extras = new Bundle(1);
9598        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9599
9600        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9601                packageName, extras, null, null, new int[] {userId});
9602        try {
9603            IActivityManager am = ActivityManagerNative.getDefault();
9604            final boolean isSystem =
9605                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9606            if (isSystem && am.isUserRunning(userId, false)) {
9607                // The just-installed/enabled app is bundled on the system, so presumed
9608                // to be able to run automatically without needing an explicit launch.
9609                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9610                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9611                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9612                        .setPackage(packageName);
9613                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9614                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9615            }
9616        } catch (RemoteException e) {
9617            // shouldn't happen
9618            Slog.w(TAG, "Unable to bootstrap installed package", e);
9619        }
9620    }
9621
9622    @Override
9623    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9624            int userId) {
9625        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9626        PackageSetting pkgSetting;
9627        final int uid = Binder.getCallingUid();
9628        enforceCrossUserPermission(uid, userId, true, true,
9629                "setApplicationHiddenSetting for user " + userId);
9630
9631        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9632            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9633            return false;
9634        }
9635
9636        long callingId = Binder.clearCallingIdentity();
9637        try {
9638            boolean sendAdded = false;
9639            boolean sendRemoved = false;
9640            // writer
9641            synchronized (mPackages) {
9642                pkgSetting = mSettings.mPackages.get(packageName);
9643                if (pkgSetting == null) {
9644                    return false;
9645                }
9646                if (pkgSetting.getHidden(userId) != hidden) {
9647                    pkgSetting.setHidden(hidden, userId);
9648                    mSettings.writePackageRestrictionsLPr(userId);
9649                    if (hidden) {
9650                        sendRemoved = true;
9651                    } else {
9652                        sendAdded = true;
9653                    }
9654                }
9655            }
9656            if (sendAdded) {
9657                sendPackageAddedForUser(packageName, pkgSetting, userId);
9658                return true;
9659            }
9660            if (sendRemoved) {
9661                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9662                        "hiding pkg");
9663                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9664                return true;
9665            }
9666        } finally {
9667            Binder.restoreCallingIdentity(callingId);
9668        }
9669        return false;
9670    }
9671
9672    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9673            int userId) {
9674        final PackageRemovedInfo info = new PackageRemovedInfo();
9675        info.removedPackage = packageName;
9676        info.removedUsers = new int[] {userId};
9677        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9678        info.sendBroadcast(false, false, false);
9679    }
9680
9681    /**
9682     * Returns true if application is not found or there was an error. Otherwise it returns
9683     * the hidden state of the package for the given user.
9684     */
9685    @Override
9686    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9687        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9688        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9689                false, "getApplicationHidden for user " + userId);
9690        PackageSetting pkgSetting;
9691        long callingId = Binder.clearCallingIdentity();
9692        try {
9693            // writer
9694            synchronized (mPackages) {
9695                pkgSetting = mSettings.mPackages.get(packageName);
9696                if (pkgSetting == null) {
9697                    return true;
9698                }
9699                return pkgSetting.getHidden(userId);
9700            }
9701        } finally {
9702            Binder.restoreCallingIdentity(callingId);
9703        }
9704    }
9705
9706    /**
9707     * @hide
9708     */
9709    @Override
9710    public int installExistingPackageAsUser(String packageName, int userId) {
9711        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9712                null);
9713        PackageSetting pkgSetting;
9714        final int uid = Binder.getCallingUid();
9715        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9716                + userId);
9717        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9718            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9719        }
9720
9721        long callingId = Binder.clearCallingIdentity();
9722        try {
9723            boolean sendAdded = false;
9724
9725            // writer
9726            synchronized (mPackages) {
9727                pkgSetting = mSettings.mPackages.get(packageName);
9728                if (pkgSetting == null) {
9729                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9730                }
9731                if (!pkgSetting.getInstalled(userId)) {
9732                    pkgSetting.setInstalled(true, userId);
9733                    pkgSetting.setHidden(false, userId);
9734                    mSettings.writePackageRestrictionsLPr(userId);
9735                    sendAdded = true;
9736                }
9737            }
9738
9739            if (sendAdded) {
9740                sendPackageAddedForUser(packageName, pkgSetting, userId);
9741            }
9742        } finally {
9743            Binder.restoreCallingIdentity(callingId);
9744        }
9745
9746        return PackageManager.INSTALL_SUCCEEDED;
9747    }
9748
9749    boolean isUserRestricted(int userId, String restrictionKey) {
9750        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9751        if (restrictions.getBoolean(restrictionKey, false)) {
9752            Log.w(TAG, "User is restricted: " + restrictionKey);
9753            return true;
9754        }
9755        return false;
9756    }
9757
9758    @Override
9759    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9760        mContext.enforceCallingOrSelfPermission(
9761                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9762                "Only package verification agents can verify applications");
9763
9764        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9765        final PackageVerificationResponse response = new PackageVerificationResponse(
9766                verificationCode, Binder.getCallingUid());
9767        msg.arg1 = id;
9768        msg.obj = response;
9769        mHandler.sendMessage(msg);
9770    }
9771
9772    @Override
9773    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9774            long millisecondsToDelay) {
9775        mContext.enforceCallingOrSelfPermission(
9776                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9777                "Only package verification agents can extend verification timeouts");
9778
9779        final PackageVerificationState state = mPendingVerification.get(id);
9780        final PackageVerificationResponse response = new PackageVerificationResponse(
9781                verificationCodeAtTimeout, Binder.getCallingUid());
9782
9783        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9784            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9785        }
9786        if (millisecondsToDelay < 0) {
9787            millisecondsToDelay = 0;
9788        }
9789        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9790                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9791            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9792        }
9793
9794        if ((state != null) && !state.timeoutExtended()) {
9795            state.extendTimeout();
9796
9797            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9798            msg.arg1 = id;
9799            msg.obj = response;
9800            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9801        }
9802    }
9803
9804    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9805            int verificationCode, UserHandle user) {
9806        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9807        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9808        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9809        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9810        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9811
9812        mContext.sendBroadcastAsUser(intent, user,
9813                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9814    }
9815
9816    private ComponentName matchComponentForVerifier(String packageName,
9817            List<ResolveInfo> receivers) {
9818        ActivityInfo targetReceiver = null;
9819
9820        final int NR = receivers.size();
9821        for (int i = 0; i < NR; i++) {
9822            final ResolveInfo info = receivers.get(i);
9823            if (info.activityInfo == null) {
9824                continue;
9825            }
9826
9827            if (packageName.equals(info.activityInfo.packageName)) {
9828                targetReceiver = info.activityInfo;
9829                break;
9830            }
9831        }
9832
9833        if (targetReceiver == null) {
9834            return null;
9835        }
9836
9837        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9838    }
9839
9840    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9841            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9842        if (pkgInfo.verifiers.length == 0) {
9843            return null;
9844        }
9845
9846        final int N = pkgInfo.verifiers.length;
9847        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9848        for (int i = 0; i < N; i++) {
9849            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9850
9851            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9852                    receivers);
9853            if (comp == null) {
9854                continue;
9855            }
9856
9857            final int verifierUid = getUidForVerifier(verifierInfo);
9858            if (verifierUid == -1) {
9859                continue;
9860            }
9861
9862            if (DEBUG_VERIFY) {
9863                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9864                        + " with the correct signature");
9865            }
9866            sufficientVerifiers.add(comp);
9867            verificationState.addSufficientVerifier(verifierUid);
9868        }
9869
9870        return sufficientVerifiers;
9871    }
9872
9873    private int getUidForVerifier(VerifierInfo verifierInfo) {
9874        synchronized (mPackages) {
9875            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9876            if (pkg == null) {
9877                return -1;
9878            } else if (pkg.mSignatures.length != 1) {
9879                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9880                        + " has more than one signature; ignoring");
9881                return -1;
9882            }
9883
9884            /*
9885             * If the public key of the package's signature does not match
9886             * our expected public key, then this is a different package and
9887             * we should skip.
9888             */
9889
9890            final byte[] expectedPublicKey;
9891            try {
9892                final Signature verifierSig = pkg.mSignatures[0];
9893                final PublicKey publicKey = verifierSig.getPublicKey();
9894                expectedPublicKey = publicKey.getEncoded();
9895            } catch (CertificateException e) {
9896                return -1;
9897            }
9898
9899            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9900
9901            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9902                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9903                        + " does not have the expected public key; ignoring");
9904                return -1;
9905            }
9906
9907            return pkg.applicationInfo.uid;
9908        }
9909    }
9910
9911    @Override
9912    public void finishPackageInstall(int token) {
9913        enforceSystemOrRoot("Only the system is allowed to finish installs");
9914
9915        if (DEBUG_INSTALL) {
9916            Slog.v(TAG, "BM finishing package install for " + token);
9917        }
9918
9919        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9920        mHandler.sendMessage(msg);
9921    }
9922
9923    /**
9924     * Get the verification agent timeout.
9925     *
9926     * @return verification timeout in milliseconds
9927     */
9928    private long getVerificationTimeout() {
9929        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9930                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9931                DEFAULT_VERIFICATION_TIMEOUT);
9932    }
9933
9934    /**
9935     * Get the default verification agent response code.
9936     *
9937     * @return default verification response code
9938     */
9939    private int getDefaultVerificationResponse() {
9940        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9941                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9942                DEFAULT_VERIFICATION_RESPONSE);
9943    }
9944
9945    /**
9946     * Check whether or not package verification has been enabled.
9947     *
9948     * @return true if verification should be performed
9949     */
9950    private boolean isVerificationEnabled(int userId, int installFlags) {
9951        if (!DEFAULT_VERIFY_ENABLE) {
9952            return false;
9953        }
9954
9955        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9956
9957        // Check if installing from ADB
9958        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9959            // Do not run verification in a test harness environment
9960            if (ActivityManager.isRunningInTestHarness()) {
9961                return false;
9962            }
9963            if (ensureVerifyAppsEnabled) {
9964                return true;
9965            }
9966            // Check if the developer does not want package verification for ADB installs
9967            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9968                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9969                return false;
9970            }
9971        }
9972
9973        if (ensureVerifyAppsEnabled) {
9974            return true;
9975        }
9976
9977        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9978                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9979    }
9980
9981    @Override
9982    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9983            throws RemoteException {
9984        mContext.enforceCallingOrSelfPermission(
9985                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9986                "Only intentfilter verification agents can verify applications");
9987
9988        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9989        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9990                Binder.getCallingUid(), verificationCode, failedDomains);
9991        msg.arg1 = id;
9992        msg.obj = response;
9993        mHandler.sendMessage(msg);
9994    }
9995
9996    @Override
9997    public int getIntentVerificationStatus(String packageName, int userId) {
9998        synchronized (mPackages) {
9999            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10000        }
10001    }
10002
10003    @Override
10004    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10005        mContext.enforceCallingOrSelfPermission(
10006                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10007
10008        boolean result = false;
10009        synchronized (mPackages) {
10010            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10011        }
10012        if (result) {
10013            scheduleWritePackageRestrictionsLocked(userId);
10014        }
10015        return result;
10016    }
10017
10018    @Override
10019    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10020        synchronized (mPackages) {
10021            return mSettings.getIntentFilterVerificationsLPr(packageName);
10022        }
10023    }
10024
10025    @Override
10026    public List<IntentFilter> getAllIntentFilters(String packageName) {
10027        if (TextUtils.isEmpty(packageName)) {
10028            return Collections.<IntentFilter>emptyList();
10029        }
10030        synchronized (mPackages) {
10031            PackageParser.Package pkg = mPackages.get(packageName);
10032            if (pkg == null || pkg.activities == null) {
10033                return Collections.<IntentFilter>emptyList();
10034            }
10035            final int count = pkg.activities.size();
10036            ArrayList<IntentFilter> result = new ArrayList<>();
10037            for (int n=0; n<count; n++) {
10038                PackageParser.Activity activity = pkg.activities.get(n);
10039                if (activity.intents != null || activity.intents.size() > 0) {
10040                    result.addAll(activity.intents);
10041                }
10042            }
10043            return result;
10044        }
10045    }
10046
10047    @Override
10048    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10049        mContext.enforceCallingOrSelfPermission(
10050                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10051
10052        synchronized (mPackages) {
10053            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10054            if (packageName != null) {
10055                result |= updateIntentVerificationStatus(packageName,
10056                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10057                        userId);
10058                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10059                        packageName, userId);
10060            }
10061            return result;
10062        }
10063    }
10064
10065    @Override
10066    public String getDefaultBrowserPackageName(int userId) {
10067        synchronized (mPackages) {
10068            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10069        }
10070    }
10071
10072    /**
10073     * Get the "allow unknown sources" setting.
10074     *
10075     * @return the current "allow unknown sources" setting
10076     */
10077    private int getUnknownSourcesSettings() {
10078        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10079                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10080                -1);
10081    }
10082
10083    @Override
10084    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10085        final int uid = Binder.getCallingUid();
10086        // writer
10087        synchronized (mPackages) {
10088            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10089            if (targetPackageSetting == null) {
10090                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10091            }
10092
10093            PackageSetting installerPackageSetting;
10094            if (installerPackageName != null) {
10095                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10096                if (installerPackageSetting == null) {
10097                    throw new IllegalArgumentException("Unknown installer package: "
10098                            + installerPackageName);
10099                }
10100            } else {
10101                installerPackageSetting = null;
10102            }
10103
10104            Signature[] callerSignature;
10105            Object obj = mSettings.getUserIdLPr(uid);
10106            if (obj != null) {
10107                if (obj instanceof SharedUserSetting) {
10108                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10109                } else if (obj instanceof PackageSetting) {
10110                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10111                } else {
10112                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10113                }
10114            } else {
10115                throw new SecurityException("Unknown calling uid " + uid);
10116            }
10117
10118            // Verify: can't set installerPackageName to a package that is
10119            // not signed with the same cert as the caller.
10120            if (installerPackageSetting != null) {
10121                if (compareSignatures(callerSignature,
10122                        installerPackageSetting.signatures.mSignatures)
10123                        != PackageManager.SIGNATURE_MATCH) {
10124                    throw new SecurityException(
10125                            "Caller does not have same cert as new installer package "
10126                            + installerPackageName);
10127                }
10128            }
10129
10130            // Verify: if target already has an installer package, it must
10131            // be signed with the same cert as the caller.
10132            if (targetPackageSetting.installerPackageName != null) {
10133                PackageSetting setting = mSettings.mPackages.get(
10134                        targetPackageSetting.installerPackageName);
10135                // If the currently set package isn't valid, then it's always
10136                // okay to change it.
10137                if (setting != null) {
10138                    if (compareSignatures(callerSignature,
10139                            setting.signatures.mSignatures)
10140                            != PackageManager.SIGNATURE_MATCH) {
10141                        throw new SecurityException(
10142                                "Caller does not have same cert as old installer package "
10143                                + targetPackageSetting.installerPackageName);
10144                    }
10145                }
10146            }
10147
10148            // Okay!
10149            targetPackageSetting.installerPackageName = installerPackageName;
10150            scheduleWriteSettingsLocked();
10151        }
10152    }
10153
10154    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10155        // Queue up an async operation since the package installation may take a little while.
10156        mHandler.post(new Runnable() {
10157            public void run() {
10158                mHandler.removeCallbacks(this);
10159                 // Result object to be returned
10160                PackageInstalledInfo res = new PackageInstalledInfo();
10161                res.returnCode = currentStatus;
10162                res.uid = -1;
10163                res.pkg = null;
10164                res.removedInfo = new PackageRemovedInfo();
10165                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10166                    args.doPreInstall(res.returnCode);
10167                    synchronized (mInstallLock) {
10168                        installPackageLI(args, res);
10169                    }
10170                    args.doPostInstall(res.returnCode, res.uid);
10171                }
10172
10173                // A restore should be performed at this point if (a) the install
10174                // succeeded, (b) the operation is not an update, and (c) the new
10175                // package has not opted out of backup participation.
10176                final boolean update = res.removedInfo.removedPackage != null;
10177                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10178                boolean doRestore = !update
10179                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10180
10181                // Set up the post-install work request bookkeeping.  This will be used
10182                // and cleaned up by the post-install event handling regardless of whether
10183                // there's a restore pass performed.  Token values are >= 1.
10184                int token;
10185                if (mNextInstallToken < 0) mNextInstallToken = 1;
10186                token = mNextInstallToken++;
10187
10188                PostInstallData data = new PostInstallData(args, res);
10189                mRunningInstalls.put(token, data);
10190                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10191
10192                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10193                    // Pass responsibility to the Backup Manager.  It will perform a
10194                    // restore if appropriate, then pass responsibility back to the
10195                    // Package Manager to run the post-install observer callbacks
10196                    // and broadcasts.
10197                    IBackupManager bm = IBackupManager.Stub.asInterface(
10198                            ServiceManager.getService(Context.BACKUP_SERVICE));
10199                    if (bm != null) {
10200                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10201                                + " to BM for possible restore");
10202                        try {
10203                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10204                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10205                            } else {
10206                                doRestore = false;
10207                            }
10208                        } catch (RemoteException e) {
10209                            // can't happen; the backup manager is local
10210                        } catch (Exception e) {
10211                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10212                            doRestore = false;
10213                        }
10214                    } else {
10215                        Slog.e(TAG, "Backup Manager not found!");
10216                        doRestore = false;
10217                    }
10218                }
10219
10220                if (!doRestore) {
10221                    // No restore possible, or the Backup Manager was mysteriously not
10222                    // available -- just fire the post-install work request directly.
10223                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10224                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10225                    mHandler.sendMessage(msg);
10226                }
10227            }
10228        });
10229    }
10230
10231    private abstract class HandlerParams {
10232        private static final int MAX_RETRIES = 4;
10233
10234        /**
10235         * Number of times startCopy() has been attempted and had a non-fatal
10236         * error.
10237         */
10238        private int mRetries = 0;
10239
10240        /** User handle for the user requesting the information or installation. */
10241        private final UserHandle mUser;
10242
10243        HandlerParams(UserHandle user) {
10244            mUser = user;
10245        }
10246
10247        UserHandle getUser() {
10248            return mUser;
10249        }
10250
10251        final boolean startCopy() {
10252            boolean res;
10253            try {
10254                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10255
10256                if (++mRetries > MAX_RETRIES) {
10257                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10258                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10259                    handleServiceError();
10260                    return false;
10261                } else {
10262                    handleStartCopy();
10263                    res = true;
10264                }
10265            } catch (RemoteException e) {
10266                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10267                mHandler.sendEmptyMessage(MCS_RECONNECT);
10268                res = false;
10269            }
10270            handleReturnCode();
10271            return res;
10272        }
10273
10274        final void serviceError() {
10275            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10276            handleServiceError();
10277            handleReturnCode();
10278        }
10279
10280        abstract void handleStartCopy() throws RemoteException;
10281        abstract void handleServiceError();
10282        abstract void handleReturnCode();
10283    }
10284
10285    class MeasureParams extends HandlerParams {
10286        private final PackageStats mStats;
10287        private boolean mSuccess;
10288
10289        private final IPackageStatsObserver mObserver;
10290
10291        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10292            super(new UserHandle(stats.userHandle));
10293            mObserver = observer;
10294            mStats = stats;
10295        }
10296
10297        @Override
10298        public String toString() {
10299            return "MeasureParams{"
10300                + Integer.toHexString(System.identityHashCode(this))
10301                + " " + mStats.packageName + "}";
10302        }
10303
10304        @Override
10305        void handleStartCopy() throws RemoteException {
10306            synchronized (mInstallLock) {
10307                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10308            }
10309
10310            if (mSuccess) {
10311                final boolean mounted;
10312                if (Environment.isExternalStorageEmulated()) {
10313                    mounted = true;
10314                } else {
10315                    final String status = Environment.getExternalStorageState();
10316                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10317                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10318                }
10319
10320                if (mounted) {
10321                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10322
10323                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10324                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10325
10326                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10327                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10328
10329                    // Always subtract cache size, since it's a subdirectory
10330                    mStats.externalDataSize -= mStats.externalCacheSize;
10331
10332                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10333                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10334
10335                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10336                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10337                }
10338            }
10339        }
10340
10341        @Override
10342        void handleReturnCode() {
10343            if (mObserver != null) {
10344                try {
10345                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10346                } catch (RemoteException e) {
10347                    Slog.i(TAG, "Observer no longer exists.");
10348                }
10349            }
10350        }
10351
10352        @Override
10353        void handleServiceError() {
10354            Slog.e(TAG, "Could not measure application " + mStats.packageName
10355                            + " external storage");
10356        }
10357    }
10358
10359    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10360            throws RemoteException {
10361        long result = 0;
10362        for (File path : paths) {
10363            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10364        }
10365        return result;
10366    }
10367
10368    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10369        for (File path : paths) {
10370            try {
10371                mcs.clearDirectory(path.getAbsolutePath());
10372            } catch (RemoteException e) {
10373            }
10374        }
10375    }
10376
10377    static class OriginInfo {
10378        /**
10379         * Location where install is coming from, before it has been
10380         * copied/renamed into place. This could be a single monolithic APK
10381         * file, or a cluster directory. This location may be untrusted.
10382         */
10383        final File file;
10384        final String cid;
10385
10386        /**
10387         * Flag indicating that {@link #file} or {@link #cid} has already been
10388         * staged, meaning downstream users don't need to defensively copy the
10389         * contents.
10390         */
10391        final boolean staged;
10392
10393        /**
10394         * Flag indicating that {@link #file} or {@link #cid} is an already
10395         * installed app that is being moved.
10396         */
10397        final boolean existing;
10398
10399        final String resolvedPath;
10400        final File resolvedFile;
10401
10402        static OriginInfo fromNothing() {
10403            return new OriginInfo(null, null, false, false);
10404        }
10405
10406        static OriginInfo fromUntrustedFile(File file) {
10407            return new OriginInfo(file, null, false, false);
10408        }
10409
10410        static OriginInfo fromExistingFile(File file) {
10411            return new OriginInfo(file, null, false, true);
10412        }
10413
10414        static OriginInfo fromStagedFile(File file) {
10415            return new OriginInfo(file, null, true, false);
10416        }
10417
10418        static OriginInfo fromStagedContainer(String cid) {
10419            return new OriginInfo(null, cid, true, false);
10420        }
10421
10422        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10423            this.file = file;
10424            this.cid = cid;
10425            this.staged = staged;
10426            this.existing = existing;
10427
10428            if (cid != null) {
10429                resolvedPath = PackageHelper.getSdDir(cid);
10430                resolvedFile = new File(resolvedPath);
10431            } else if (file != null) {
10432                resolvedPath = file.getAbsolutePath();
10433                resolvedFile = file;
10434            } else {
10435                resolvedPath = null;
10436                resolvedFile = null;
10437            }
10438        }
10439    }
10440
10441    class MoveInfo {
10442        final int moveId;
10443        final String fromUuid;
10444        final String toUuid;
10445        final String packageName;
10446        final String dataAppName;
10447        final int appId;
10448        final String seinfo;
10449
10450        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10451                String dataAppName, int appId, String seinfo) {
10452            this.moveId = moveId;
10453            this.fromUuid = fromUuid;
10454            this.toUuid = toUuid;
10455            this.packageName = packageName;
10456            this.dataAppName = dataAppName;
10457            this.appId = appId;
10458            this.seinfo = seinfo;
10459        }
10460    }
10461
10462    class InstallParams extends HandlerParams {
10463        final OriginInfo origin;
10464        final MoveInfo move;
10465        final IPackageInstallObserver2 observer;
10466        int installFlags;
10467        final String installerPackageName;
10468        final String volumeUuid;
10469        final VerificationParams verificationParams;
10470        private InstallArgs mArgs;
10471        private int mRet;
10472        final String packageAbiOverride;
10473        final String[] grantedRuntimePermissions;
10474
10475
10476        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10477                int installFlags, String installerPackageName, String volumeUuid,
10478                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10479                String[] grantedPermissions) {
10480            super(user);
10481            this.origin = origin;
10482            this.move = move;
10483            this.observer = observer;
10484            this.installFlags = installFlags;
10485            this.installerPackageName = installerPackageName;
10486            this.volumeUuid = volumeUuid;
10487            this.verificationParams = verificationParams;
10488            this.packageAbiOverride = packageAbiOverride;
10489            this.grantedRuntimePermissions = grantedPermissions;
10490        }
10491
10492        @Override
10493        public String toString() {
10494            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10495                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10496        }
10497
10498        public ManifestDigest getManifestDigest() {
10499            if (verificationParams == null) {
10500                return null;
10501            }
10502            return verificationParams.getManifestDigest();
10503        }
10504
10505        private int installLocationPolicy(PackageInfoLite pkgLite) {
10506            String packageName = pkgLite.packageName;
10507            int installLocation = pkgLite.installLocation;
10508            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10509            // reader
10510            synchronized (mPackages) {
10511                PackageParser.Package pkg = mPackages.get(packageName);
10512                if (pkg != null) {
10513                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10514                        // Check for downgrading.
10515                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10516                            try {
10517                                checkDowngrade(pkg, pkgLite);
10518                            } catch (PackageManagerException e) {
10519                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10520                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10521                            }
10522                        }
10523                        // Check for updated system application.
10524                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10525                            if (onSd) {
10526                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10527                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10528                            }
10529                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10530                        } else {
10531                            if (onSd) {
10532                                // Install flag overrides everything.
10533                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10534                            }
10535                            // If current upgrade specifies particular preference
10536                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10537                                // Application explicitly specified internal.
10538                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10539                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10540                                // App explictly prefers external. Let policy decide
10541                            } else {
10542                                // Prefer previous location
10543                                if (isExternal(pkg)) {
10544                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10545                                }
10546                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10547                            }
10548                        }
10549                    } else {
10550                        // Invalid install. Return error code
10551                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10552                    }
10553                }
10554            }
10555            // All the special cases have been taken care of.
10556            // Return result based on recommended install location.
10557            if (onSd) {
10558                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10559            }
10560            return pkgLite.recommendedInstallLocation;
10561        }
10562
10563        /*
10564         * Invoke remote method to get package information and install
10565         * location values. Override install location based on default
10566         * policy if needed and then create install arguments based
10567         * on the install location.
10568         */
10569        public void handleStartCopy() throws RemoteException {
10570            int ret = PackageManager.INSTALL_SUCCEEDED;
10571
10572            // If we're already staged, we've firmly committed to an install location
10573            if (origin.staged) {
10574                if (origin.file != null) {
10575                    installFlags |= PackageManager.INSTALL_INTERNAL;
10576                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10577                } else if (origin.cid != null) {
10578                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10579                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10580                } else {
10581                    throw new IllegalStateException("Invalid stage location");
10582                }
10583            }
10584
10585            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10586            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10587
10588            PackageInfoLite pkgLite = null;
10589
10590            if (onInt && onSd) {
10591                // Check if both bits are set.
10592                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10593                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10594            } else {
10595                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10596                        packageAbiOverride);
10597
10598                /*
10599                 * If we have too little free space, try to free cache
10600                 * before giving up.
10601                 */
10602                if (!origin.staged && pkgLite.recommendedInstallLocation
10603                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10604                    // TODO: focus freeing disk space on the target device
10605                    final StorageManager storage = StorageManager.from(mContext);
10606                    final long lowThreshold = storage.getStorageLowBytes(
10607                            Environment.getDataDirectory());
10608
10609                    final long sizeBytes = mContainerService.calculateInstalledSize(
10610                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10611
10612                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10613                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10614                                installFlags, packageAbiOverride);
10615                    }
10616
10617                    /*
10618                     * The cache free must have deleted the file we
10619                     * downloaded to install.
10620                     *
10621                     * TODO: fix the "freeCache" call to not delete
10622                     *       the file we care about.
10623                     */
10624                    if (pkgLite.recommendedInstallLocation
10625                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10626                        pkgLite.recommendedInstallLocation
10627                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10628                    }
10629                }
10630            }
10631
10632            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10633                int loc = pkgLite.recommendedInstallLocation;
10634                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10635                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10636                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10637                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10638                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10639                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10640                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10641                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10642                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10643                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10644                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10645                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10646                } else {
10647                    // Override with defaults if needed.
10648                    loc = installLocationPolicy(pkgLite);
10649                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10650                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10651                    } else if (!onSd && !onInt) {
10652                        // Override install location with flags
10653                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10654                            // Set the flag to install on external media.
10655                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10656                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10657                        } else {
10658                            // Make sure the flag for installing on external
10659                            // media is unset
10660                            installFlags |= PackageManager.INSTALL_INTERNAL;
10661                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10662                        }
10663                    }
10664                }
10665            }
10666
10667            final InstallArgs args = createInstallArgs(this);
10668            mArgs = args;
10669
10670            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10671                 /*
10672                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10673                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10674                 */
10675                int userIdentifier = getUser().getIdentifier();
10676                if (userIdentifier == UserHandle.USER_ALL
10677                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10678                    userIdentifier = UserHandle.USER_OWNER;
10679                }
10680
10681                /*
10682                 * Determine if we have any installed package verifiers. If we
10683                 * do, then we'll defer to them to verify the packages.
10684                 */
10685                final int requiredUid = mRequiredVerifierPackage == null ? -1
10686                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10687                if (!origin.existing && requiredUid != -1
10688                        && isVerificationEnabled(userIdentifier, installFlags)) {
10689                    final Intent verification = new Intent(
10690                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10691                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10692                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10693                            PACKAGE_MIME_TYPE);
10694                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10695
10696                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10697                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10698                            0 /* TODO: Which userId? */);
10699
10700                    if (DEBUG_VERIFY) {
10701                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10702                                + verification.toString() + " with " + pkgLite.verifiers.length
10703                                + " optional verifiers");
10704                    }
10705
10706                    final int verificationId = mPendingVerificationToken++;
10707
10708                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10709
10710                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10711                            installerPackageName);
10712
10713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10714                            installFlags);
10715
10716                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10717                            pkgLite.packageName);
10718
10719                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10720                            pkgLite.versionCode);
10721
10722                    if (verificationParams != null) {
10723                        if (verificationParams.getVerificationURI() != null) {
10724                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10725                                 verificationParams.getVerificationURI());
10726                        }
10727                        if (verificationParams.getOriginatingURI() != null) {
10728                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10729                                  verificationParams.getOriginatingURI());
10730                        }
10731                        if (verificationParams.getReferrer() != null) {
10732                            verification.putExtra(Intent.EXTRA_REFERRER,
10733                                  verificationParams.getReferrer());
10734                        }
10735                        if (verificationParams.getOriginatingUid() >= 0) {
10736                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10737                                  verificationParams.getOriginatingUid());
10738                        }
10739                        if (verificationParams.getInstallerUid() >= 0) {
10740                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10741                                  verificationParams.getInstallerUid());
10742                        }
10743                    }
10744
10745                    final PackageVerificationState verificationState = new PackageVerificationState(
10746                            requiredUid, args);
10747
10748                    mPendingVerification.append(verificationId, verificationState);
10749
10750                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10751                            receivers, verificationState);
10752
10753                    // Apps installed for "all" users use the device owner to verify the app
10754                    UserHandle verifierUser = getUser();
10755                    if (verifierUser == UserHandle.ALL) {
10756                        verifierUser = UserHandle.OWNER;
10757                    }
10758
10759                    /*
10760                     * If any sufficient verifiers were listed in the package
10761                     * manifest, attempt to ask them.
10762                     */
10763                    if (sufficientVerifiers != null) {
10764                        final int N = sufficientVerifiers.size();
10765                        if (N == 0) {
10766                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10767                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10768                        } else {
10769                            for (int i = 0; i < N; i++) {
10770                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10771
10772                                final Intent sufficientIntent = new Intent(verification);
10773                                sufficientIntent.setComponent(verifierComponent);
10774                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10775                            }
10776                        }
10777                    }
10778
10779                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10780                            mRequiredVerifierPackage, receivers);
10781                    if (ret == PackageManager.INSTALL_SUCCEEDED
10782                            && mRequiredVerifierPackage != null) {
10783                        /*
10784                         * Send the intent to the required verification agent,
10785                         * but only start the verification timeout after the
10786                         * target BroadcastReceivers have run.
10787                         */
10788                        verification.setComponent(requiredVerifierComponent);
10789                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10790                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10791                                new BroadcastReceiver() {
10792                                    @Override
10793                                    public void onReceive(Context context, Intent intent) {
10794                                        final Message msg = mHandler
10795                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10796                                        msg.arg1 = verificationId;
10797                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10798                                    }
10799                                }, null, 0, null, null);
10800
10801                        /*
10802                         * We don't want the copy to proceed until verification
10803                         * succeeds, so null out this field.
10804                         */
10805                        mArgs = null;
10806                    }
10807                } else {
10808                    /*
10809                     * No package verification is enabled, so immediately start
10810                     * the remote call to initiate copy using temporary file.
10811                     */
10812                    ret = args.copyApk(mContainerService, true);
10813                }
10814            }
10815
10816            mRet = ret;
10817        }
10818
10819        @Override
10820        void handleReturnCode() {
10821            // If mArgs is null, then MCS couldn't be reached. When it
10822            // reconnects, it will try again to install. At that point, this
10823            // will succeed.
10824            if (mArgs != null) {
10825                processPendingInstall(mArgs, mRet);
10826            }
10827        }
10828
10829        @Override
10830        void handleServiceError() {
10831            mArgs = createInstallArgs(this);
10832            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10833        }
10834
10835        public boolean isForwardLocked() {
10836            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10837        }
10838    }
10839
10840    /**
10841     * Used during creation of InstallArgs
10842     *
10843     * @param installFlags package installation flags
10844     * @return true if should be installed on external storage
10845     */
10846    private static boolean installOnExternalAsec(int installFlags) {
10847        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10848            return false;
10849        }
10850        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10851            return true;
10852        }
10853        return false;
10854    }
10855
10856    /**
10857     * Used during creation of InstallArgs
10858     *
10859     * @param installFlags package installation flags
10860     * @return true if should be installed as forward locked
10861     */
10862    private static boolean installForwardLocked(int installFlags) {
10863        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10864    }
10865
10866    private InstallArgs createInstallArgs(InstallParams params) {
10867        if (params.move != null) {
10868            return new MoveInstallArgs(params);
10869        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10870            return new AsecInstallArgs(params);
10871        } else {
10872            return new FileInstallArgs(params);
10873        }
10874    }
10875
10876    /**
10877     * Create args that describe an existing installed package. Typically used
10878     * when cleaning up old installs, or used as a move source.
10879     */
10880    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10881            String resourcePath, String[] instructionSets) {
10882        final boolean isInAsec;
10883        if (installOnExternalAsec(installFlags)) {
10884            /* Apps on SD card are always in ASEC containers. */
10885            isInAsec = true;
10886        } else if (installForwardLocked(installFlags)
10887                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10888            /*
10889             * Forward-locked apps are only in ASEC containers if they're the
10890             * new style
10891             */
10892            isInAsec = true;
10893        } else {
10894            isInAsec = false;
10895        }
10896
10897        if (isInAsec) {
10898            return new AsecInstallArgs(codePath, instructionSets,
10899                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10900        } else {
10901            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10902        }
10903    }
10904
10905    static abstract class InstallArgs {
10906        /** @see InstallParams#origin */
10907        final OriginInfo origin;
10908        /** @see InstallParams#move */
10909        final MoveInfo move;
10910
10911        final IPackageInstallObserver2 observer;
10912        // Always refers to PackageManager flags only
10913        final int installFlags;
10914        final String installerPackageName;
10915        final String volumeUuid;
10916        final ManifestDigest manifestDigest;
10917        final UserHandle user;
10918        final String abiOverride;
10919        final String[] installGrantPermissions;
10920
10921        // The list of instruction sets supported by this app. This is currently
10922        // only used during the rmdex() phase to clean up resources. We can get rid of this
10923        // if we move dex files under the common app path.
10924        /* nullable */ String[] instructionSets;
10925
10926        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10927                int installFlags, String installerPackageName, String volumeUuid,
10928                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10929                String abiOverride, String[] installGrantPermissions) {
10930            this.origin = origin;
10931            this.move = move;
10932            this.installFlags = installFlags;
10933            this.observer = observer;
10934            this.installerPackageName = installerPackageName;
10935            this.volumeUuid = volumeUuid;
10936            this.manifestDigest = manifestDigest;
10937            this.user = user;
10938            this.instructionSets = instructionSets;
10939            this.abiOverride = abiOverride;
10940            this.installGrantPermissions = installGrantPermissions;
10941        }
10942
10943        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10944        abstract int doPreInstall(int status);
10945
10946        /**
10947         * Rename package into final resting place. All paths on the given
10948         * scanned package should be updated to reflect the rename.
10949         */
10950        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10951        abstract int doPostInstall(int status, int uid);
10952
10953        /** @see PackageSettingBase#codePathString */
10954        abstract String getCodePath();
10955        /** @see PackageSettingBase#resourcePathString */
10956        abstract String getResourcePath();
10957
10958        // Need installer lock especially for dex file removal.
10959        abstract void cleanUpResourcesLI();
10960        abstract boolean doPostDeleteLI(boolean delete);
10961
10962        /**
10963         * Called before the source arguments are copied. This is used mostly
10964         * for MoveParams when it needs to read the source file to put it in the
10965         * destination.
10966         */
10967        int doPreCopy() {
10968            return PackageManager.INSTALL_SUCCEEDED;
10969        }
10970
10971        /**
10972         * Called after the source arguments are copied. This is used mostly for
10973         * MoveParams when it needs to read the source file to put it in the
10974         * destination.
10975         *
10976         * @return
10977         */
10978        int doPostCopy(int uid) {
10979            return PackageManager.INSTALL_SUCCEEDED;
10980        }
10981
10982        protected boolean isFwdLocked() {
10983            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10984        }
10985
10986        protected boolean isExternalAsec() {
10987            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10988        }
10989
10990        UserHandle getUser() {
10991            return user;
10992        }
10993    }
10994
10995    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10996        if (!allCodePaths.isEmpty()) {
10997            if (instructionSets == null) {
10998                throw new IllegalStateException("instructionSet == null");
10999            }
11000            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11001            for (String codePath : allCodePaths) {
11002                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11003                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11004                    if (retCode < 0) {
11005                        Slog.w(TAG, "Couldn't remove dex file for package: "
11006                                + " at location " + codePath + ", retcode=" + retCode);
11007                        // we don't consider this to be a failure of the core package deletion
11008                    }
11009                }
11010            }
11011        }
11012    }
11013
11014    /**
11015     * Logic to handle installation of non-ASEC applications, including copying
11016     * and renaming logic.
11017     */
11018    class FileInstallArgs extends InstallArgs {
11019        private File codeFile;
11020        private File resourceFile;
11021
11022        // Example topology:
11023        // /data/app/com.example/base.apk
11024        // /data/app/com.example/split_foo.apk
11025        // /data/app/com.example/lib/arm/libfoo.so
11026        // /data/app/com.example/lib/arm64/libfoo.so
11027        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11028
11029        /** New install */
11030        FileInstallArgs(InstallParams params) {
11031            super(params.origin, params.move, params.observer, params.installFlags,
11032                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11033                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11034                    params.grantedRuntimePermissions);
11035            if (isFwdLocked()) {
11036                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11037            }
11038        }
11039
11040        /** Existing install */
11041        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11042            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11043                    null, null);
11044            this.codeFile = (codePath != null) ? new File(codePath) : null;
11045            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11046        }
11047
11048        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11049            if (origin.staged) {
11050                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11051                codeFile = origin.file;
11052                resourceFile = origin.file;
11053                return PackageManager.INSTALL_SUCCEEDED;
11054            }
11055
11056            try {
11057                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11058                codeFile = tempDir;
11059                resourceFile = tempDir;
11060            } catch (IOException e) {
11061                Slog.w(TAG, "Failed to create copy file: " + e);
11062                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11063            }
11064
11065            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11066                @Override
11067                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11068                    if (!FileUtils.isValidExtFilename(name)) {
11069                        throw new IllegalArgumentException("Invalid filename: " + name);
11070                    }
11071                    try {
11072                        final File file = new File(codeFile, name);
11073                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11074                                O_RDWR | O_CREAT, 0644);
11075                        Os.chmod(file.getAbsolutePath(), 0644);
11076                        return new ParcelFileDescriptor(fd);
11077                    } catch (ErrnoException e) {
11078                        throw new RemoteException("Failed to open: " + e.getMessage());
11079                    }
11080                }
11081            };
11082
11083            int ret = PackageManager.INSTALL_SUCCEEDED;
11084            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11085            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11086                Slog.e(TAG, "Failed to copy package");
11087                return ret;
11088            }
11089
11090            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11091            NativeLibraryHelper.Handle handle = null;
11092            try {
11093                handle = NativeLibraryHelper.Handle.create(codeFile);
11094                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11095                        abiOverride);
11096            } catch (IOException e) {
11097                Slog.e(TAG, "Copying native libraries failed", e);
11098                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11099            } finally {
11100                IoUtils.closeQuietly(handle);
11101            }
11102
11103            return ret;
11104        }
11105
11106        int doPreInstall(int status) {
11107            if (status != PackageManager.INSTALL_SUCCEEDED) {
11108                cleanUp();
11109            }
11110            return status;
11111        }
11112
11113        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11114            if (status != PackageManager.INSTALL_SUCCEEDED) {
11115                cleanUp();
11116                return false;
11117            }
11118
11119            final File targetDir = codeFile.getParentFile();
11120            final File beforeCodeFile = codeFile;
11121            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11122
11123            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11124            try {
11125                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11126            } catch (ErrnoException e) {
11127                Slog.w(TAG, "Failed to rename", e);
11128                return false;
11129            }
11130
11131            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11132                Slog.w(TAG, "Failed to restorecon");
11133                return false;
11134            }
11135
11136            // Reflect the rename internally
11137            codeFile = afterCodeFile;
11138            resourceFile = afterCodeFile;
11139
11140            // Reflect the rename in scanned details
11141            pkg.codePath = afterCodeFile.getAbsolutePath();
11142            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11143                    pkg.baseCodePath);
11144            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11145                    pkg.splitCodePaths);
11146
11147            // Reflect the rename in app info
11148            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11149            pkg.applicationInfo.setCodePath(pkg.codePath);
11150            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11151            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11152            pkg.applicationInfo.setResourcePath(pkg.codePath);
11153            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11154            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11155
11156            return true;
11157        }
11158
11159        int doPostInstall(int status, int uid) {
11160            if (status != PackageManager.INSTALL_SUCCEEDED) {
11161                cleanUp();
11162            }
11163            return status;
11164        }
11165
11166        @Override
11167        String getCodePath() {
11168            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11169        }
11170
11171        @Override
11172        String getResourcePath() {
11173            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11174        }
11175
11176        private boolean cleanUp() {
11177            if (codeFile == null || !codeFile.exists()) {
11178                return false;
11179            }
11180
11181            if (codeFile.isDirectory()) {
11182                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11183            } else {
11184                codeFile.delete();
11185            }
11186
11187            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11188                resourceFile.delete();
11189            }
11190
11191            return true;
11192        }
11193
11194        void cleanUpResourcesLI() {
11195            // Try enumerating all code paths before deleting
11196            List<String> allCodePaths = Collections.EMPTY_LIST;
11197            if (codeFile != null && codeFile.exists()) {
11198                try {
11199                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11200                    allCodePaths = pkg.getAllCodePaths();
11201                } catch (PackageParserException e) {
11202                    // Ignored; we tried our best
11203                }
11204            }
11205
11206            cleanUp();
11207            removeDexFiles(allCodePaths, instructionSets);
11208        }
11209
11210        boolean doPostDeleteLI(boolean delete) {
11211            // XXX err, shouldn't we respect the delete flag?
11212            cleanUpResourcesLI();
11213            return true;
11214        }
11215    }
11216
11217    private boolean isAsecExternal(String cid) {
11218        final String asecPath = PackageHelper.getSdFilesystem(cid);
11219        return !asecPath.startsWith(mAsecInternalPath);
11220    }
11221
11222    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11223            PackageManagerException {
11224        if (copyRet < 0) {
11225            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11226                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11227                throw new PackageManagerException(copyRet, message);
11228            }
11229        }
11230    }
11231
11232    /**
11233     * Extract the MountService "container ID" from the full code path of an
11234     * .apk.
11235     */
11236    static String cidFromCodePath(String fullCodePath) {
11237        int eidx = fullCodePath.lastIndexOf("/");
11238        String subStr1 = fullCodePath.substring(0, eidx);
11239        int sidx = subStr1.lastIndexOf("/");
11240        return subStr1.substring(sidx+1, eidx);
11241    }
11242
11243    /**
11244     * Logic to handle installation of ASEC applications, including copying and
11245     * renaming logic.
11246     */
11247    class AsecInstallArgs extends InstallArgs {
11248        static final String RES_FILE_NAME = "pkg.apk";
11249        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11250
11251        String cid;
11252        String packagePath;
11253        String resourcePath;
11254
11255        /** New install */
11256        AsecInstallArgs(InstallParams params) {
11257            super(params.origin, params.move, params.observer, params.installFlags,
11258                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11259                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11260                    params.grantedRuntimePermissions);
11261        }
11262
11263        /** Existing install */
11264        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11265                        boolean isExternal, boolean isForwardLocked) {
11266            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11267                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11268                    instructionSets, null, null);
11269            // Hackily pretend we're still looking at a full code path
11270            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11271                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11272            }
11273
11274            // Extract cid from fullCodePath
11275            int eidx = fullCodePath.lastIndexOf("/");
11276            String subStr1 = fullCodePath.substring(0, eidx);
11277            int sidx = subStr1.lastIndexOf("/");
11278            cid = subStr1.substring(sidx+1, eidx);
11279            setMountPath(subStr1);
11280        }
11281
11282        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11283            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11284                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11285                    instructionSets, null, null);
11286            this.cid = cid;
11287            setMountPath(PackageHelper.getSdDir(cid));
11288        }
11289
11290        void createCopyFile() {
11291            cid = mInstallerService.allocateExternalStageCidLegacy();
11292        }
11293
11294        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11295            if (origin.staged) {
11296                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11297                cid = origin.cid;
11298                setMountPath(PackageHelper.getSdDir(cid));
11299                return PackageManager.INSTALL_SUCCEEDED;
11300            }
11301
11302            if (temp) {
11303                createCopyFile();
11304            } else {
11305                /*
11306                 * Pre-emptively destroy the container since it's destroyed if
11307                 * copying fails due to it existing anyway.
11308                 */
11309                PackageHelper.destroySdDir(cid);
11310            }
11311
11312            final String newMountPath = imcs.copyPackageToContainer(
11313                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11314                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11315
11316            if (newMountPath != null) {
11317                setMountPath(newMountPath);
11318                return PackageManager.INSTALL_SUCCEEDED;
11319            } else {
11320                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11321            }
11322        }
11323
11324        @Override
11325        String getCodePath() {
11326            return packagePath;
11327        }
11328
11329        @Override
11330        String getResourcePath() {
11331            return resourcePath;
11332        }
11333
11334        int doPreInstall(int status) {
11335            if (status != PackageManager.INSTALL_SUCCEEDED) {
11336                // Destroy container
11337                PackageHelper.destroySdDir(cid);
11338            } else {
11339                boolean mounted = PackageHelper.isContainerMounted(cid);
11340                if (!mounted) {
11341                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11342                            Process.SYSTEM_UID);
11343                    if (newMountPath != null) {
11344                        setMountPath(newMountPath);
11345                    } else {
11346                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11347                    }
11348                }
11349            }
11350            return status;
11351        }
11352
11353        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11354            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11355            String newMountPath = null;
11356            if (PackageHelper.isContainerMounted(cid)) {
11357                // Unmount the container
11358                if (!PackageHelper.unMountSdDir(cid)) {
11359                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11360                    return false;
11361                }
11362            }
11363            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11364                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11365                        " which might be stale. Will try to clean up.");
11366                // Clean up the stale container and proceed to recreate.
11367                if (!PackageHelper.destroySdDir(newCacheId)) {
11368                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11369                    return false;
11370                }
11371                // Successfully cleaned up stale container. Try to rename again.
11372                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11373                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11374                            + " inspite of cleaning it up.");
11375                    return false;
11376                }
11377            }
11378            if (!PackageHelper.isContainerMounted(newCacheId)) {
11379                Slog.w(TAG, "Mounting container " + newCacheId);
11380                newMountPath = PackageHelper.mountSdDir(newCacheId,
11381                        getEncryptKey(), Process.SYSTEM_UID);
11382            } else {
11383                newMountPath = PackageHelper.getSdDir(newCacheId);
11384            }
11385            if (newMountPath == null) {
11386                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11387                return false;
11388            }
11389            Log.i(TAG, "Succesfully renamed " + cid +
11390                    " to " + newCacheId +
11391                    " at new path: " + newMountPath);
11392            cid = newCacheId;
11393
11394            final File beforeCodeFile = new File(packagePath);
11395            setMountPath(newMountPath);
11396            final File afterCodeFile = new File(packagePath);
11397
11398            // Reflect the rename in scanned details
11399            pkg.codePath = afterCodeFile.getAbsolutePath();
11400            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11401                    pkg.baseCodePath);
11402            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11403                    pkg.splitCodePaths);
11404
11405            // Reflect the rename in app info
11406            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11407            pkg.applicationInfo.setCodePath(pkg.codePath);
11408            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11409            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11410            pkg.applicationInfo.setResourcePath(pkg.codePath);
11411            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11412            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11413
11414            return true;
11415        }
11416
11417        private void setMountPath(String mountPath) {
11418            final File mountFile = new File(mountPath);
11419
11420            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11421            if (monolithicFile.exists()) {
11422                packagePath = monolithicFile.getAbsolutePath();
11423                if (isFwdLocked()) {
11424                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11425                } else {
11426                    resourcePath = packagePath;
11427                }
11428            } else {
11429                packagePath = mountFile.getAbsolutePath();
11430                resourcePath = packagePath;
11431            }
11432        }
11433
11434        int doPostInstall(int status, int uid) {
11435            if (status != PackageManager.INSTALL_SUCCEEDED) {
11436                cleanUp();
11437            } else {
11438                final int groupOwner;
11439                final String protectedFile;
11440                if (isFwdLocked()) {
11441                    groupOwner = UserHandle.getSharedAppGid(uid);
11442                    protectedFile = RES_FILE_NAME;
11443                } else {
11444                    groupOwner = -1;
11445                    protectedFile = null;
11446                }
11447
11448                if (uid < Process.FIRST_APPLICATION_UID
11449                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11450                    Slog.e(TAG, "Failed to finalize " + cid);
11451                    PackageHelper.destroySdDir(cid);
11452                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11453                }
11454
11455                boolean mounted = PackageHelper.isContainerMounted(cid);
11456                if (!mounted) {
11457                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11458                }
11459            }
11460            return status;
11461        }
11462
11463        private void cleanUp() {
11464            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11465
11466            // Destroy secure container
11467            PackageHelper.destroySdDir(cid);
11468        }
11469
11470        private List<String> getAllCodePaths() {
11471            final File codeFile = new File(getCodePath());
11472            if (codeFile != null && codeFile.exists()) {
11473                try {
11474                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11475                    return pkg.getAllCodePaths();
11476                } catch (PackageParserException e) {
11477                    // Ignored; we tried our best
11478                }
11479            }
11480            return Collections.EMPTY_LIST;
11481        }
11482
11483        void cleanUpResourcesLI() {
11484            // Enumerate all code paths before deleting
11485            cleanUpResourcesLI(getAllCodePaths());
11486        }
11487
11488        private void cleanUpResourcesLI(List<String> allCodePaths) {
11489            cleanUp();
11490            removeDexFiles(allCodePaths, instructionSets);
11491        }
11492
11493        String getPackageName() {
11494            return getAsecPackageName(cid);
11495        }
11496
11497        boolean doPostDeleteLI(boolean delete) {
11498            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11499            final List<String> allCodePaths = getAllCodePaths();
11500            boolean mounted = PackageHelper.isContainerMounted(cid);
11501            if (mounted) {
11502                // Unmount first
11503                if (PackageHelper.unMountSdDir(cid)) {
11504                    mounted = false;
11505                }
11506            }
11507            if (!mounted && delete) {
11508                cleanUpResourcesLI(allCodePaths);
11509            }
11510            return !mounted;
11511        }
11512
11513        @Override
11514        int doPreCopy() {
11515            if (isFwdLocked()) {
11516                if (!PackageHelper.fixSdPermissions(cid,
11517                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11518                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11519                }
11520            }
11521
11522            return PackageManager.INSTALL_SUCCEEDED;
11523        }
11524
11525        @Override
11526        int doPostCopy(int uid) {
11527            if (isFwdLocked()) {
11528                if (uid < Process.FIRST_APPLICATION_UID
11529                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11530                                RES_FILE_NAME)) {
11531                    Slog.e(TAG, "Failed to finalize " + cid);
11532                    PackageHelper.destroySdDir(cid);
11533                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11534                }
11535            }
11536
11537            return PackageManager.INSTALL_SUCCEEDED;
11538        }
11539    }
11540
11541    /**
11542     * Logic to handle movement of existing installed applications.
11543     */
11544    class MoveInstallArgs extends InstallArgs {
11545        private File codeFile;
11546        private File resourceFile;
11547
11548        /** New install */
11549        MoveInstallArgs(InstallParams params) {
11550            super(params.origin, params.move, params.observer, params.installFlags,
11551                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11552                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11553                    params.grantedRuntimePermissions);
11554        }
11555
11556        int copyApk(IMediaContainerService imcs, boolean temp) {
11557            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11558                    + move.fromUuid + " to " + move.toUuid);
11559            synchronized (mInstaller) {
11560                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11561                        move.dataAppName, move.appId, move.seinfo) != 0) {
11562                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11563                }
11564            }
11565
11566            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11567            resourceFile = codeFile;
11568            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11569
11570            return PackageManager.INSTALL_SUCCEEDED;
11571        }
11572
11573        int doPreInstall(int status) {
11574            if (status != PackageManager.INSTALL_SUCCEEDED) {
11575                cleanUp(move.toUuid);
11576            }
11577            return status;
11578        }
11579
11580        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11581            if (status != PackageManager.INSTALL_SUCCEEDED) {
11582                cleanUp(move.toUuid);
11583                return false;
11584            }
11585
11586            // Reflect the move in app info
11587            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11588            pkg.applicationInfo.setCodePath(pkg.codePath);
11589            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11590            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11591            pkg.applicationInfo.setResourcePath(pkg.codePath);
11592            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11593            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11594
11595            return true;
11596        }
11597
11598        int doPostInstall(int status, int uid) {
11599            if (status == PackageManager.INSTALL_SUCCEEDED) {
11600                cleanUp(move.fromUuid);
11601            } else {
11602                cleanUp(move.toUuid);
11603            }
11604            return status;
11605        }
11606
11607        @Override
11608        String getCodePath() {
11609            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11610        }
11611
11612        @Override
11613        String getResourcePath() {
11614            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11615        }
11616
11617        private boolean cleanUp(String volumeUuid) {
11618            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11619                    move.dataAppName);
11620            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11621            synchronized (mInstallLock) {
11622                // Clean up both app data and code
11623                removeDataDirsLI(volumeUuid, move.packageName);
11624                if (codeFile.isDirectory()) {
11625                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11626                } else {
11627                    codeFile.delete();
11628                }
11629            }
11630            return true;
11631        }
11632
11633        void cleanUpResourcesLI() {
11634            throw new UnsupportedOperationException();
11635        }
11636
11637        boolean doPostDeleteLI(boolean delete) {
11638            throw new UnsupportedOperationException();
11639        }
11640    }
11641
11642    static String getAsecPackageName(String packageCid) {
11643        int idx = packageCid.lastIndexOf("-");
11644        if (idx == -1) {
11645            return packageCid;
11646        }
11647        return packageCid.substring(0, idx);
11648    }
11649
11650    // Utility method used to create code paths based on package name and available index.
11651    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11652        String idxStr = "";
11653        int idx = 1;
11654        // Fall back to default value of idx=1 if prefix is not
11655        // part of oldCodePath
11656        if (oldCodePath != null) {
11657            String subStr = oldCodePath;
11658            // Drop the suffix right away
11659            if (suffix != null && subStr.endsWith(suffix)) {
11660                subStr = subStr.substring(0, subStr.length() - suffix.length());
11661            }
11662            // If oldCodePath already contains prefix find out the
11663            // ending index to either increment or decrement.
11664            int sidx = subStr.lastIndexOf(prefix);
11665            if (sidx != -1) {
11666                subStr = subStr.substring(sidx + prefix.length());
11667                if (subStr != null) {
11668                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11669                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11670                    }
11671                    try {
11672                        idx = Integer.parseInt(subStr);
11673                        if (idx <= 1) {
11674                            idx++;
11675                        } else {
11676                            idx--;
11677                        }
11678                    } catch(NumberFormatException e) {
11679                    }
11680                }
11681            }
11682        }
11683        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11684        return prefix + idxStr;
11685    }
11686
11687    private File getNextCodePath(File targetDir, String packageName) {
11688        int suffix = 1;
11689        File result;
11690        do {
11691            result = new File(targetDir, packageName + "-" + suffix);
11692            suffix++;
11693        } while (result.exists());
11694        return result;
11695    }
11696
11697    // Utility method that returns the relative package path with respect
11698    // to the installation directory. Like say for /data/data/com.test-1.apk
11699    // string com.test-1 is returned.
11700    static String deriveCodePathName(String codePath) {
11701        if (codePath == null) {
11702            return null;
11703        }
11704        final File codeFile = new File(codePath);
11705        final String name = codeFile.getName();
11706        if (codeFile.isDirectory()) {
11707            return name;
11708        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11709            final int lastDot = name.lastIndexOf('.');
11710            return name.substring(0, lastDot);
11711        } else {
11712            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11713            return null;
11714        }
11715    }
11716
11717    class PackageInstalledInfo {
11718        String name;
11719        int uid;
11720        // The set of users that originally had this package installed.
11721        int[] origUsers;
11722        // The set of users that now have this package installed.
11723        int[] newUsers;
11724        PackageParser.Package pkg;
11725        int returnCode;
11726        String returnMsg;
11727        PackageRemovedInfo removedInfo;
11728
11729        public void setError(int code, String msg) {
11730            returnCode = code;
11731            returnMsg = msg;
11732            Slog.w(TAG, msg);
11733        }
11734
11735        public void setError(String msg, PackageParserException e) {
11736            returnCode = e.error;
11737            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11738            Slog.w(TAG, msg, e);
11739        }
11740
11741        public void setError(String msg, PackageManagerException e) {
11742            returnCode = e.error;
11743            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11744            Slog.w(TAG, msg, e);
11745        }
11746
11747        // In some error cases we want to convey more info back to the observer
11748        String origPackage;
11749        String origPermission;
11750    }
11751
11752    /*
11753     * Install a non-existing package.
11754     */
11755    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11756            UserHandle user, String installerPackageName, String volumeUuid,
11757            PackageInstalledInfo res) {
11758        // Remember this for later, in case we need to rollback this install
11759        String pkgName = pkg.packageName;
11760
11761        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11762        final boolean dataDirExists = Environment
11763                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11764        synchronized(mPackages) {
11765            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11766                // A package with the same name is already installed, though
11767                // it has been renamed to an older name.  The package we
11768                // are trying to install should be installed as an update to
11769                // the existing one, but that has not been requested, so bail.
11770                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11771                        + " without first uninstalling package running as "
11772                        + mSettings.mRenamedPackages.get(pkgName));
11773                return;
11774            }
11775            if (mPackages.containsKey(pkgName)) {
11776                // Don't allow installation over an existing package with the same name.
11777                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11778                        + " without first uninstalling.");
11779                return;
11780            }
11781        }
11782
11783        try {
11784            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11785                    System.currentTimeMillis(), user);
11786
11787            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11788            // delete the partially installed application. the data directory will have to be
11789            // restored if it was already existing
11790            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11791                // remove package from internal structures.  Note that we want deletePackageX to
11792                // delete the package data and cache directories that it created in
11793                // scanPackageLocked, unless those directories existed before we even tried to
11794                // install.
11795                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11796                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11797                                res.removedInfo, true);
11798            }
11799
11800        } catch (PackageManagerException e) {
11801            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11802        }
11803    }
11804
11805    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11806        // Can't rotate keys during boot or if sharedUser.
11807        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11808                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11809            return false;
11810        }
11811        // app is using upgradeKeySets; make sure all are valid
11812        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11813        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11814        for (int i = 0; i < upgradeKeySets.length; i++) {
11815            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11816                Slog.wtf(TAG, "Package "
11817                         + (oldPs.name != null ? oldPs.name : "<null>")
11818                         + " contains upgrade-key-set reference to unknown key-set: "
11819                         + upgradeKeySets[i]
11820                         + " reverting to signatures check.");
11821                return false;
11822            }
11823        }
11824        return true;
11825    }
11826
11827    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11828        // Upgrade keysets are being used.  Determine if new package has a superset of the
11829        // required keys.
11830        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11831        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11832        for (int i = 0; i < upgradeKeySets.length; i++) {
11833            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11834            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11835                return true;
11836            }
11837        }
11838        return false;
11839    }
11840
11841    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11842            UserHandle user, String installerPackageName, String volumeUuid,
11843            PackageInstalledInfo res) {
11844        final PackageParser.Package oldPackage;
11845        final String pkgName = pkg.packageName;
11846        final int[] allUsers;
11847        final boolean[] perUserInstalled;
11848
11849        // First find the old package info and check signatures
11850        synchronized(mPackages) {
11851            oldPackage = mPackages.get(pkgName);
11852            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11853            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11854            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11855                if(!checkUpgradeKeySetLP(ps, pkg)) {
11856                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11857                            "New package not signed by keys specified by upgrade-keysets: "
11858                            + pkgName);
11859                    return;
11860                }
11861            } else {
11862                // default to original signature matching
11863                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11864                    != PackageManager.SIGNATURE_MATCH) {
11865                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11866                            "New package has a different signature: " + pkgName);
11867                    return;
11868                }
11869            }
11870
11871            // In case of rollback, remember per-user/profile install state
11872            allUsers = sUserManager.getUserIds();
11873            perUserInstalled = new boolean[allUsers.length];
11874            for (int i = 0; i < allUsers.length; i++) {
11875                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11876            }
11877        }
11878
11879        boolean sysPkg = (isSystemApp(oldPackage));
11880        if (sysPkg) {
11881            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11882                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11883        } else {
11884            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11885                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11886        }
11887    }
11888
11889    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11890            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11891            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11892            String volumeUuid, PackageInstalledInfo res) {
11893        String pkgName = deletedPackage.packageName;
11894        boolean deletedPkg = true;
11895        boolean updatedSettings = false;
11896
11897        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11898                + deletedPackage);
11899        long origUpdateTime;
11900        if (pkg.mExtras != null) {
11901            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11902        } else {
11903            origUpdateTime = 0;
11904        }
11905
11906        // First delete the existing package while retaining the data directory
11907        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11908                res.removedInfo, true)) {
11909            // If the existing package wasn't successfully deleted
11910            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11911            deletedPkg = false;
11912        } else {
11913            // Successfully deleted the old package; proceed with replace.
11914
11915            // If deleted package lived in a container, give users a chance to
11916            // relinquish resources before killing.
11917            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11918                if (DEBUG_INSTALL) {
11919                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11920                }
11921                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11922                final ArrayList<String> pkgList = new ArrayList<String>(1);
11923                pkgList.add(deletedPackage.applicationInfo.packageName);
11924                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11925            }
11926
11927            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11928            try {
11929                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11930                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11931                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11932                        perUserInstalled, res, user);
11933                updatedSettings = true;
11934            } catch (PackageManagerException e) {
11935                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11936            }
11937        }
11938
11939        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11940            // remove package from internal structures.  Note that we want deletePackageX to
11941            // delete the package data and cache directories that it created in
11942            // scanPackageLocked, unless those directories existed before we even tried to
11943            // install.
11944            if(updatedSettings) {
11945                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11946                deletePackageLI(
11947                        pkgName, null, true, allUsers, perUserInstalled,
11948                        PackageManager.DELETE_KEEP_DATA,
11949                                res.removedInfo, true);
11950            }
11951            // Since we failed to install the new package we need to restore the old
11952            // package that we deleted.
11953            if (deletedPkg) {
11954                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11955                File restoreFile = new File(deletedPackage.codePath);
11956                // Parse old package
11957                boolean oldExternal = isExternal(deletedPackage);
11958                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11959                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11960                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11961                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11962                try {
11963                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11964                } catch (PackageManagerException e) {
11965                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11966                            + e.getMessage());
11967                    return;
11968                }
11969                // Restore of old package succeeded. Update permissions.
11970                // writer
11971                synchronized (mPackages) {
11972                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11973                            UPDATE_PERMISSIONS_ALL);
11974                    // can downgrade to reader
11975                    mSettings.writeLPr();
11976                }
11977                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11978            }
11979        }
11980    }
11981
11982    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11983            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11984            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11985            String volumeUuid, PackageInstalledInfo res) {
11986        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11987                + ", old=" + deletedPackage);
11988        boolean disabledSystem = false;
11989        boolean updatedSettings = false;
11990        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11991        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11992                != 0) {
11993            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11994        }
11995        String packageName = deletedPackage.packageName;
11996        if (packageName == null) {
11997            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11998                    "Attempt to delete null packageName.");
11999            return;
12000        }
12001        PackageParser.Package oldPkg;
12002        PackageSetting oldPkgSetting;
12003        // reader
12004        synchronized (mPackages) {
12005            oldPkg = mPackages.get(packageName);
12006            oldPkgSetting = mSettings.mPackages.get(packageName);
12007            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12008                    (oldPkgSetting == null)) {
12009                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12010                        "Couldn't find package:" + packageName + " information");
12011                return;
12012            }
12013        }
12014
12015        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12016
12017        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12018        res.removedInfo.removedPackage = packageName;
12019        // Remove existing system package
12020        removePackageLI(oldPkgSetting, true);
12021        // writer
12022        synchronized (mPackages) {
12023            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12024            if (!disabledSystem && deletedPackage != null) {
12025                // We didn't need to disable the .apk as a current system package,
12026                // which means we are replacing another update that is already
12027                // installed.  We need to make sure to delete the older one's .apk.
12028                res.removedInfo.args = createInstallArgsForExisting(0,
12029                        deletedPackage.applicationInfo.getCodePath(),
12030                        deletedPackage.applicationInfo.getResourcePath(),
12031                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12032            } else {
12033                res.removedInfo.args = null;
12034            }
12035        }
12036
12037        // Successfully disabled the old package. Now proceed with re-installation
12038        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12039
12040        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12041        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12042
12043        PackageParser.Package newPackage = null;
12044        try {
12045            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12046            if (newPackage.mExtras != null) {
12047                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12048                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12049                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12050
12051                // is the update attempting to change shared user? that isn't going to work...
12052                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12053                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12054                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12055                            + " to " + newPkgSetting.sharedUser);
12056                    updatedSettings = true;
12057                }
12058            }
12059
12060            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12061                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12062                        perUserInstalled, res, user);
12063                updatedSettings = true;
12064            }
12065
12066        } catch (PackageManagerException e) {
12067            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12068        }
12069
12070        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12071            // Re installation failed. Restore old information
12072            // Remove new pkg information
12073            if (newPackage != null) {
12074                removeInstalledPackageLI(newPackage, true);
12075            }
12076            // Add back the old system package
12077            try {
12078                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12079            } catch (PackageManagerException e) {
12080                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12081            }
12082            // Restore the old system information in Settings
12083            synchronized (mPackages) {
12084                if (disabledSystem) {
12085                    mSettings.enableSystemPackageLPw(packageName);
12086                }
12087                if (updatedSettings) {
12088                    mSettings.setInstallerPackageName(packageName,
12089                            oldPkgSetting.installerPackageName);
12090                }
12091                mSettings.writeLPr();
12092            }
12093        }
12094    }
12095
12096    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12097        // Collect all used permissions in the UID
12098        ArraySet<String> usedPermissions = new ArraySet<>();
12099        final int packageCount = su.packages.size();
12100        for (int i = 0; i < packageCount; i++) {
12101            PackageSetting ps = su.packages.valueAt(i);
12102            if (ps.pkg == null) {
12103                continue;
12104            }
12105            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12106            for (int j = 0; j < requestedPermCount; j++) {
12107                String permission = ps.pkg.requestedPermissions.get(j);
12108                BasePermission bp = mSettings.mPermissions.get(permission);
12109                if (bp != null) {
12110                    usedPermissions.add(permission);
12111                }
12112            }
12113        }
12114
12115        PermissionsState permissionsState = su.getPermissionsState();
12116        // Prune install permissions
12117        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12118        final int installPermCount = installPermStates.size();
12119        for (int i = installPermCount - 1; i >= 0;  i--) {
12120            PermissionState permissionState = installPermStates.get(i);
12121            if (!usedPermissions.contains(permissionState.getName())) {
12122                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12123                if (bp != null) {
12124                    permissionsState.revokeInstallPermission(bp);
12125                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12126                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12127                }
12128            }
12129        }
12130
12131        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12132
12133        // Prune runtime permissions
12134        for (int userId : allUserIds) {
12135            List<PermissionState> runtimePermStates = permissionsState
12136                    .getRuntimePermissionStates(userId);
12137            final int runtimePermCount = runtimePermStates.size();
12138            for (int i = runtimePermCount - 1; i >= 0; i--) {
12139                PermissionState permissionState = runtimePermStates.get(i);
12140                if (!usedPermissions.contains(permissionState.getName())) {
12141                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12142                    if (bp != null) {
12143                        permissionsState.revokeRuntimePermission(bp, userId);
12144                        permissionsState.updatePermissionFlags(bp, userId,
12145                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12146                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12147                                runtimePermissionChangedUserIds, userId);
12148                    }
12149                }
12150            }
12151        }
12152
12153        return runtimePermissionChangedUserIds;
12154    }
12155
12156    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12157            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12158            UserHandle user) {
12159        String pkgName = newPackage.packageName;
12160        synchronized (mPackages) {
12161            //write settings. the installStatus will be incomplete at this stage.
12162            //note that the new package setting would have already been
12163            //added to mPackages. It hasn't been persisted yet.
12164            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12165            mSettings.writeLPr();
12166        }
12167
12168        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12169
12170        synchronized (mPackages) {
12171            updatePermissionsLPw(newPackage.packageName, newPackage,
12172                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12173                            ? UPDATE_PERMISSIONS_ALL : 0));
12174            // For system-bundled packages, we assume that installing an upgraded version
12175            // of the package implies that the user actually wants to run that new code,
12176            // so we enable the package.
12177            PackageSetting ps = mSettings.mPackages.get(pkgName);
12178            if (ps != null) {
12179                if (isSystemApp(newPackage)) {
12180                    // NB: implicit assumption that system package upgrades apply to all users
12181                    if (DEBUG_INSTALL) {
12182                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12183                    }
12184                    if (res.origUsers != null) {
12185                        for (int userHandle : res.origUsers) {
12186                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12187                                    userHandle, installerPackageName);
12188                        }
12189                    }
12190                    // Also convey the prior install/uninstall state
12191                    if (allUsers != null && perUserInstalled != null) {
12192                        for (int i = 0; i < allUsers.length; i++) {
12193                            if (DEBUG_INSTALL) {
12194                                Slog.d(TAG, "    user " + allUsers[i]
12195                                        + " => " + perUserInstalled[i]);
12196                            }
12197                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12198                        }
12199                        // these install state changes will be persisted in the
12200                        // upcoming call to mSettings.writeLPr().
12201                    }
12202                }
12203                // It's implied that when a user requests installation, they want the app to be
12204                // installed and enabled.
12205                int userId = user.getIdentifier();
12206                if (userId != UserHandle.USER_ALL) {
12207                    ps.setInstalled(true, userId);
12208                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12209                }
12210            }
12211            res.name = pkgName;
12212            res.uid = newPackage.applicationInfo.uid;
12213            res.pkg = newPackage;
12214            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12215            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12216            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12217            //to update install status
12218            mSettings.writeLPr();
12219        }
12220    }
12221
12222    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12223        final int installFlags = args.installFlags;
12224        final String installerPackageName = args.installerPackageName;
12225        final String volumeUuid = args.volumeUuid;
12226        final File tmpPackageFile = new File(args.getCodePath());
12227        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12228        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12229                || (args.volumeUuid != null));
12230        boolean replace = false;
12231        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12232        if (args.move != null) {
12233            // moving a complete application; perfom an initial scan on the new install location
12234            scanFlags |= SCAN_INITIAL;
12235        }
12236        // Result object to be returned
12237        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12238
12239        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12240        // Retrieve PackageSettings and parse package
12241        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12242                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12243                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12244        PackageParser pp = new PackageParser();
12245        pp.setSeparateProcesses(mSeparateProcesses);
12246        pp.setDisplayMetrics(mMetrics);
12247
12248        final PackageParser.Package pkg;
12249        try {
12250            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12251        } catch (PackageParserException e) {
12252            res.setError("Failed parse during installPackageLI", e);
12253            return;
12254        }
12255
12256        // Mark that we have an install time CPU ABI override.
12257        pkg.cpuAbiOverride = args.abiOverride;
12258
12259        String pkgName = res.name = pkg.packageName;
12260        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12261            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12262                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12263                return;
12264            }
12265        }
12266
12267        try {
12268            pp.collectCertificates(pkg, parseFlags);
12269            pp.collectManifestDigest(pkg);
12270        } catch (PackageParserException e) {
12271            res.setError("Failed collect during installPackageLI", e);
12272            return;
12273        }
12274
12275        /* If the installer passed in a manifest digest, compare it now. */
12276        if (args.manifestDigest != null) {
12277            if (DEBUG_INSTALL) {
12278                final String parsedManifest = pkg.manifestDigest == null ? "null"
12279                        : pkg.manifestDigest.toString();
12280                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12281                        + parsedManifest);
12282            }
12283
12284            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12285                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12286                return;
12287            }
12288        } else if (DEBUG_INSTALL) {
12289            final String parsedManifest = pkg.manifestDigest == null
12290                    ? "null" : pkg.manifestDigest.toString();
12291            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12292        }
12293
12294        // Get rid of all references to package scan path via parser.
12295        pp = null;
12296        String oldCodePath = null;
12297        boolean systemApp = false;
12298        synchronized (mPackages) {
12299            // Check if installing already existing package
12300            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12301                String oldName = mSettings.mRenamedPackages.get(pkgName);
12302                if (pkg.mOriginalPackages != null
12303                        && pkg.mOriginalPackages.contains(oldName)
12304                        && mPackages.containsKey(oldName)) {
12305                    // This package is derived from an original package,
12306                    // and this device has been updating from that original
12307                    // name.  We must continue using the original name, so
12308                    // rename the new package here.
12309                    pkg.setPackageName(oldName);
12310                    pkgName = pkg.packageName;
12311                    replace = true;
12312                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12313                            + oldName + " pkgName=" + pkgName);
12314                } else if (mPackages.containsKey(pkgName)) {
12315                    // This package, under its official name, already exists
12316                    // on the device; we should replace it.
12317                    replace = true;
12318                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12319                }
12320
12321                // Prevent apps opting out from runtime permissions
12322                if (replace) {
12323                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12324                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12325                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12326                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12327                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12328                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12329                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12330                                        + " doesn't support runtime permissions but the old"
12331                                        + " target SDK " + oldTargetSdk + " does.");
12332                        return;
12333                    }
12334                }
12335            }
12336
12337            PackageSetting ps = mSettings.mPackages.get(pkgName);
12338            if (ps != null) {
12339                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12340
12341                // Quick sanity check that we're signed correctly if updating;
12342                // we'll check this again later when scanning, but we want to
12343                // bail early here before tripping over redefined permissions.
12344                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12345                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12346                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12347                                + pkg.packageName + " upgrade keys do not match the "
12348                                + "previously installed version");
12349                        return;
12350                    }
12351                } else {
12352                    try {
12353                        verifySignaturesLP(ps, pkg);
12354                    } catch (PackageManagerException e) {
12355                        res.setError(e.error, e.getMessage());
12356                        return;
12357                    }
12358                }
12359
12360                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12361                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12362                    systemApp = (ps.pkg.applicationInfo.flags &
12363                            ApplicationInfo.FLAG_SYSTEM) != 0;
12364                }
12365                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12366            }
12367
12368            // Check whether the newly-scanned package wants to define an already-defined perm
12369            int N = pkg.permissions.size();
12370            for (int i = N-1; i >= 0; i--) {
12371                PackageParser.Permission perm = pkg.permissions.get(i);
12372                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12373                if (bp != null) {
12374                    // If the defining package is signed with our cert, it's okay.  This
12375                    // also includes the "updating the same package" case, of course.
12376                    // "updating same package" could also involve key-rotation.
12377                    final boolean sigsOk;
12378                    if (bp.sourcePackage.equals(pkg.packageName)
12379                            && (bp.packageSetting instanceof PackageSetting)
12380                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12381                                    scanFlags))) {
12382                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12383                    } else {
12384                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12385                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12386                    }
12387                    if (!sigsOk) {
12388                        // If the owning package is the system itself, we log but allow
12389                        // install to proceed; we fail the install on all other permission
12390                        // redefinitions.
12391                        if (!bp.sourcePackage.equals("android")) {
12392                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12393                                    + pkg.packageName + " attempting to redeclare permission "
12394                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12395                            res.origPermission = perm.info.name;
12396                            res.origPackage = bp.sourcePackage;
12397                            return;
12398                        } else {
12399                            Slog.w(TAG, "Package " + pkg.packageName
12400                                    + " attempting to redeclare system permission "
12401                                    + perm.info.name + "; ignoring new declaration");
12402                            pkg.permissions.remove(i);
12403                        }
12404                    }
12405                }
12406            }
12407
12408        }
12409
12410        if (systemApp && onExternal) {
12411            // Disable updates to system apps on sdcard
12412            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12413                    "Cannot install updates to system apps on sdcard");
12414            return;
12415        }
12416
12417        if (args.move != null) {
12418            // We did an in-place move, so dex is ready to roll
12419            scanFlags |= SCAN_NO_DEX;
12420            scanFlags |= SCAN_MOVE;
12421
12422            synchronized (mPackages) {
12423                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12424                if (ps == null) {
12425                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12426                            "Missing settings for moved package " + pkgName);
12427                }
12428
12429                // We moved the entire application as-is, so bring over the
12430                // previously derived ABI information.
12431                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12432                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12433            }
12434
12435        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12436            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12437            scanFlags |= SCAN_NO_DEX;
12438
12439            try {
12440                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12441                        true /* extract libs */);
12442            } catch (PackageManagerException pme) {
12443                Slog.e(TAG, "Error deriving application ABI", pme);
12444                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12445                return;
12446            }
12447
12448            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12449            int result = mPackageDexOptimizer
12450                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12451                            false /* defer */, false /* inclDependencies */,
12452                            true /* boot complete */);
12453            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12454                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12455                return;
12456            }
12457        }
12458
12459        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12460            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12461            return;
12462        }
12463
12464        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12465
12466        if (replace) {
12467            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12468                    installerPackageName, volumeUuid, res);
12469        } else {
12470            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12471                    args.user, installerPackageName, volumeUuid, res);
12472        }
12473        synchronized (mPackages) {
12474            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12475            if (ps != null) {
12476                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12477            }
12478        }
12479    }
12480
12481    private void startIntentFilterVerifications(int userId, boolean replacing,
12482            PackageParser.Package pkg) {
12483        if (mIntentFilterVerifierComponent == null) {
12484            Slog.w(TAG, "No IntentFilter verification will not be done as "
12485                    + "there is no IntentFilterVerifier available!");
12486            return;
12487        }
12488
12489        final int verifierUid = getPackageUid(
12490                mIntentFilterVerifierComponent.getPackageName(),
12491                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12492
12493        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12494        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12495        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12496        mHandler.sendMessage(msg);
12497    }
12498
12499    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12500            PackageParser.Package pkg) {
12501        int size = pkg.activities.size();
12502        if (size == 0) {
12503            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12504                    "No activity, so no need to verify any IntentFilter!");
12505            return;
12506        }
12507
12508        final boolean hasDomainURLs = hasDomainURLs(pkg);
12509        if (!hasDomainURLs) {
12510            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12511                    "No domain URLs, so no need to verify any IntentFilter!");
12512            return;
12513        }
12514
12515        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12516                + " if any IntentFilter from the " + size
12517                + " Activities needs verification ...");
12518
12519        int count = 0;
12520        final String packageName = pkg.packageName;
12521
12522        synchronized (mPackages) {
12523            // If this is a new install and we see that we've already run verification for this
12524            // package, we have nothing to do: it means the state was restored from backup.
12525            if (!replacing) {
12526                IntentFilterVerificationInfo ivi =
12527                        mSettings.getIntentFilterVerificationLPr(packageName);
12528                if (ivi != null) {
12529                    if (DEBUG_DOMAIN_VERIFICATION) {
12530                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12531                                + ivi.getStatusString());
12532                    }
12533                    return;
12534                }
12535            }
12536
12537            // If any filters need to be verified, then all need to be.
12538            boolean needToVerify = false;
12539            for (PackageParser.Activity a : pkg.activities) {
12540                for (ActivityIntentInfo filter : a.intents) {
12541                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12542                        if (DEBUG_DOMAIN_VERIFICATION) {
12543                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12544                        }
12545                        needToVerify = true;
12546                        break;
12547                    }
12548                }
12549            }
12550
12551            if (needToVerify) {
12552                final int verificationId = mIntentFilterVerificationToken++;
12553                for (PackageParser.Activity a : pkg.activities) {
12554                    for (ActivityIntentInfo filter : a.intents) {
12555                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12556                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12557                                    "Verification needed for IntentFilter:" + filter.toString());
12558                            mIntentFilterVerifier.addOneIntentFilterVerification(
12559                                    verifierUid, userId, verificationId, filter, packageName);
12560                            count++;
12561                        }
12562                    }
12563                }
12564            }
12565        }
12566
12567        if (count > 0) {
12568            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12569                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12570                    +  " for userId:" + userId);
12571            mIntentFilterVerifier.startVerifications(userId);
12572        } else {
12573            if (DEBUG_DOMAIN_VERIFICATION) {
12574                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12575            }
12576        }
12577    }
12578
12579    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12580        final ComponentName cn  = filter.activity.getComponentName();
12581        final String packageName = cn.getPackageName();
12582
12583        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12584                packageName);
12585        if (ivi == null) {
12586            return true;
12587        }
12588        int status = ivi.getStatus();
12589        switch (status) {
12590            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12591            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12592                return true;
12593
12594            default:
12595                // Nothing to do
12596                return false;
12597        }
12598    }
12599
12600    private static boolean isMultiArch(PackageSetting ps) {
12601        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12602    }
12603
12604    private static boolean isMultiArch(ApplicationInfo info) {
12605        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12606    }
12607
12608    private static boolean isExternal(PackageParser.Package pkg) {
12609        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12610    }
12611
12612    private static boolean isExternal(PackageSetting ps) {
12613        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12614    }
12615
12616    private static boolean isExternal(ApplicationInfo info) {
12617        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12618    }
12619
12620    private static boolean isSystemApp(PackageParser.Package pkg) {
12621        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12622    }
12623
12624    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12625        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12626    }
12627
12628    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12629        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12630    }
12631
12632    private static boolean isSystemApp(PackageSetting ps) {
12633        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12634    }
12635
12636    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12637        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12638    }
12639
12640    private int packageFlagsToInstallFlags(PackageSetting ps) {
12641        int installFlags = 0;
12642        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12643            // This existing package was an external ASEC install when we have
12644            // the external flag without a UUID
12645            installFlags |= PackageManager.INSTALL_EXTERNAL;
12646        }
12647        if (ps.isForwardLocked()) {
12648            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12649        }
12650        return installFlags;
12651    }
12652
12653    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12654        if (isExternal(pkg)) {
12655            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12656                return StorageManager.UUID_PRIMARY_PHYSICAL;
12657            } else {
12658                return pkg.volumeUuid;
12659            }
12660        } else {
12661            return StorageManager.UUID_PRIVATE_INTERNAL;
12662        }
12663    }
12664
12665    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12666        if (isExternal(pkg)) {
12667            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12668                return mSettings.getExternalVersion();
12669            } else {
12670                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12671            }
12672        } else {
12673            return mSettings.getInternalVersion();
12674        }
12675    }
12676
12677    private void deleteTempPackageFiles() {
12678        final FilenameFilter filter = new FilenameFilter() {
12679            public boolean accept(File dir, String name) {
12680                return name.startsWith("vmdl") && name.endsWith(".tmp");
12681            }
12682        };
12683        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12684            file.delete();
12685        }
12686    }
12687
12688    @Override
12689    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12690            int flags) {
12691        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12692                flags);
12693    }
12694
12695    @Override
12696    public void deletePackage(final String packageName,
12697            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12698        mContext.enforceCallingOrSelfPermission(
12699                android.Manifest.permission.DELETE_PACKAGES, null);
12700        Preconditions.checkNotNull(packageName);
12701        Preconditions.checkNotNull(observer);
12702        final int uid = Binder.getCallingUid();
12703        if (UserHandle.getUserId(uid) != userId) {
12704            mContext.enforceCallingPermission(
12705                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12706                    "deletePackage for user " + userId);
12707        }
12708        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12709            try {
12710                observer.onPackageDeleted(packageName,
12711                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12712            } catch (RemoteException re) {
12713            }
12714            return;
12715        }
12716
12717        boolean uninstallBlocked = false;
12718        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12719            int[] users = sUserManager.getUserIds();
12720            for (int i = 0; i < users.length; ++i) {
12721                if (getBlockUninstallForUser(packageName, users[i])) {
12722                    uninstallBlocked = true;
12723                    break;
12724                }
12725            }
12726        } else {
12727            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12728        }
12729        if (uninstallBlocked) {
12730            try {
12731                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12732                        null);
12733            } catch (RemoteException re) {
12734            }
12735            return;
12736        }
12737
12738        if (DEBUG_REMOVE) {
12739            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12740        }
12741        // Queue up an async operation since the package deletion may take a little while.
12742        mHandler.post(new Runnable() {
12743            public void run() {
12744                mHandler.removeCallbacks(this);
12745                final int returnCode = deletePackageX(packageName, userId, flags);
12746                if (observer != null) {
12747                    try {
12748                        observer.onPackageDeleted(packageName, returnCode, null);
12749                    } catch (RemoteException e) {
12750                        Log.i(TAG, "Observer no longer exists.");
12751                    } //end catch
12752                } //end if
12753            } //end run
12754        });
12755    }
12756
12757    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12758        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12759                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12760        try {
12761            if (dpm != null) {
12762                if (dpm.isDeviceOwner(packageName)) {
12763                    return true;
12764                }
12765                int[] users;
12766                if (userId == UserHandle.USER_ALL) {
12767                    users = sUserManager.getUserIds();
12768                } else {
12769                    users = new int[]{userId};
12770                }
12771                for (int i = 0; i < users.length; ++i) {
12772                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12773                        return true;
12774                    }
12775                }
12776            }
12777        } catch (RemoteException e) {
12778        }
12779        return false;
12780    }
12781
12782    /**
12783     *  This method is an internal method that could be get invoked either
12784     *  to delete an installed package or to clean up a failed installation.
12785     *  After deleting an installed package, a broadcast is sent to notify any
12786     *  listeners that the package has been installed. For cleaning up a failed
12787     *  installation, the broadcast is not necessary since the package's
12788     *  installation wouldn't have sent the initial broadcast either
12789     *  The key steps in deleting a package are
12790     *  deleting the package information in internal structures like mPackages,
12791     *  deleting the packages base directories through installd
12792     *  updating mSettings to reflect current status
12793     *  persisting settings for later use
12794     *  sending a broadcast if necessary
12795     */
12796    private int deletePackageX(String packageName, int userId, int flags) {
12797        final PackageRemovedInfo info = new PackageRemovedInfo();
12798        final boolean res;
12799
12800        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12801                ? UserHandle.ALL : new UserHandle(userId);
12802
12803        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12804            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12805            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12806        }
12807
12808        boolean removedForAllUsers = false;
12809        boolean systemUpdate = false;
12810
12811        // for the uninstall-updates case and restricted profiles, remember the per-
12812        // userhandle installed state
12813        int[] allUsers;
12814        boolean[] perUserInstalled;
12815        synchronized (mPackages) {
12816            PackageSetting ps = mSettings.mPackages.get(packageName);
12817            allUsers = sUserManager.getUserIds();
12818            perUserInstalled = new boolean[allUsers.length];
12819            for (int i = 0; i < allUsers.length; i++) {
12820                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12821            }
12822        }
12823
12824        synchronized (mInstallLock) {
12825            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12826            res = deletePackageLI(packageName, removeForUser,
12827                    true, allUsers, perUserInstalled,
12828                    flags | REMOVE_CHATTY, info, true);
12829            systemUpdate = info.isRemovedPackageSystemUpdate;
12830            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12831                removedForAllUsers = true;
12832            }
12833            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12834                    + " removedForAllUsers=" + removedForAllUsers);
12835        }
12836
12837        if (res) {
12838            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12839
12840            // If the removed package was a system update, the old system package
12841            // was re-enabled; we need to broadcast this information
12842            if (systemUpdate) {
12843                Bundle extras = new Bundle(1);
12844                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12845                        ? info.removedAppId : info.uid);
12846                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12847
12848                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12849                        extras, null, null, null);
12850                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12851                        extras, null, null, null);
12852                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12853                        null, packageName, null, null);
12854            }
12855        }
12856        // Force a gc here.
12857        Runtime.getRuntime().gc();
12858        // Delete the resources here after sending the broadcast to let
12859        // other processes clean up before deleting resources.
12860        if (info.args != null) {
12861            synchronized (mInstallLock) {
12862                info.args.doPostDeleteLI(true);
12863            }
12864        }
12865
12866        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12867    }
12868
12869    class PackageRemovedInfo {
12870        String removedPackage;
12871        int uid = -1;
12872        int removedAppId = -1;
12873        int[] removedUsers = null;
12874        boolean isRemovedPackageSystemUpdate = false;
12875        // Clean up resources deleted packages.
12876        InstallArgs args = null;
12877
12878        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12879            Bundle extras = new Bundle(1);
12880            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12881            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12882            if (replacing) {
12883                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12884            }
12885            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12886            if (removedPackage != null) {
12887                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12888                        extras, null, null, removedUsers);
12889                if (fullRemove && !replacing) {
12890                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12891                            extras, null, null, removedUsers);
12892                }
12893            }
12894            if (removedAppId >= 0) {
12895                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12896                        removedUsers);
12897            }
12898        }
12899    }
12900
12901    /*
12902     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12903     * flag is not set, the data directory is removed as well.
12904     * make sure this flag is set for partially installed apps. If not its meaningless to
12905     * delete a partially installed application.
12906     */
12907    private void removePackageDataLI(PackageSetting ps,
12908            int[] allUserHandles, boolean[] perUserInstalled,
12909            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12910        String packageName = ps.name;
12911        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12912        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12913        // Retrieve object to delete permissions for shared user later on
12914        final PackageSetting deletedPs;
12915        // reader
12916        synchronized (mPackages) {
12917            deletedPs = mSettings.mPackages.get(packageName);
12918            if (outInfo != null) {
12919                outInfo.removedPackage = packageName;
12920                outInfo.removedUsers = deletedPs != null
12921                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12922                        : null;
12923            }
12924        }
12925        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12926            removeDataDirsLI(ps.volumeUuid, packageName);
12927            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12928        }
12929        // writer
12930        synchronized (mPackages) {
12931            if (deletedPs != null) {
12932                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12933                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12934                    clearDefaultBrowserIfNeeded(packageName);
12935                    if (outInfo != null) {
12936                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12937                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12938                    }
12939                    updatePermissionsLPw(deletedPs.name, null, 0);
12940                    if (deletedPs.sharedUser != null) {
12941                        // Remove permissions associated with package. Since runtime
12942                        // permissions are per user we have to kill the removed package
12943                        // or packages running under the shared user of the removed
12944                        // package if revoking the permissions requested only by the removed
12945                        // package is successful and this causes a change in gids.
12946                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12947                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12948                                    userId);
12949                            if (userIdToKill == UserHandle.USER_ALL
12950                                    || userIdToKill >= UserHandle.USER_OWNER) {
12951                                // If gids changed for this user, kill all affected packages.
12952                                mHandler.post(new Runnable() {
12953                                    @Override
12954                                    public void run() {
12955                                        // This has to happen with no lock held.
12956                                        killApplication(deletedPs.name, deletedPs.appId,
12957                                                KILL_APP_REASON_GIDS_CHANGED);
12958                                    }
12959                                });
12960                                break;
12961                            }
12962                        }
12963                    }
12964                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12965                }
12966                // make sure to preserve per-user disabled state if this removal was just
12967                // a downgrade of a system app to the factory package
12968                if (allUserHandles != null && perUserInstalled != null) {
12969                    if (DEBUG_REMOVE) {
12970                        Slog.d(TAG, "Propagating install state across downgrade");
12971                    }
12972                    for (int i = 0; i < allUserHandles.length; i++) {
12973                        if (DEBUG_REMOVE) {
12974                            Slog.d(TAG, "    user " + allUserHandles[i]
12975                                    + " => " + perUserInstalled[i]);
12976                        }
12977                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12978                    }
12979                }
12980            }
12981            // can downgrade to reader
12982            if (writeSettings) {
12983                // Save settings now
12984                mSettings.writeLPr();
12985            }
12986        }
12987        if (outInfo != null) {
12988            // A user ID was deleted here. Go through all users and remove it
12989            // from KeyStore.
12990            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12991        }
12992    }
12993
12994    static boolean locationIsPrivileged(File path) {
12995        try {
12996            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12997                    .getCanonicalPath();
12998            return path.getCanonicalPath().startsWith(privilegedAppDir);
12999        } catch (IOException e) {
13000            Slog.e(TAG, "Unable to access code path " + path);
13001        }
13002        return false;
13003    }
13004
13005    /*
13006     * Tries to delete system package.
13007     */
13008    private boolean deleteSystemPackageLI(PackageSetting newPs,
13009            int[] allUserHandles, boolean[] perUserInstalled,
13010            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13011        final boolean applyUserRestrictions
13012                = (allUserHandles != null) && (perUserInstalled != null);
13013        PackageSetting disabledPs = null;
13014        // Confirm if the system package has been updated
13015        // An updated system app can be deleted. This will also have to restore
13016        // the system pkg from system partition
13017        // reader
13018        synchronized (mPackages) {
13019            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13020        }
13021        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13022                + " disabledPs=" + disabledPs);
13023        if (disabledPs == null) {
13024            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13025            return false;
13026        } else if (DEBUG_REMOVE) {
13027            Slog.d(TAG, "Deleting system pkg from data partition");
13028        }
13029        if (DEBUG_REMOVE) {
13030            if (applyUserRestrictions) {
13031                Slog.d(TAG, "Remembering install states:");
13032                for (int i = 0; i < allUserHandles.length; i++) {
13033                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13034                }
13035            }
13036        }
13037        // Delete the updated package
13038        outInfo.isRemovedPackageSystemUpdate = true;
13039        if (disabledPs.versionCode < newPs.versionCode) {
13040            // Delete data for downgrades
13041            flags &= ~PackageManager.DELETE_KEEP_DATA;
13042        } else {
13043            // Preserve data by setting flag
13044            flags |= PackageManager.DELETE_KEEP_DATA;
13045        }
13046        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13047                allUserHandles, perUserInstalled, outInfo, writeSettings);
13048        if (!ret) {
13049            return false;
13050        }
13051        // writer
13052        synchronized (mPackages) {
13053            // Reinstate the old system package
13054            mSettings.enableSystemPackageLPw(newPs.name);
13055            // Remove any native libraries from the upgraded package.
13056            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13057        }
13058        // Install the system package
13059        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13060        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13061        if (locationIsPrivileged(disabledPs.codePath)) {
13062            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13063        }
13064
13065        final PackageParser.Package newPkg;
13066        try {
13067            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13068        } catch (PackageManagerException e) {
13069            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13070            return false;
13071        }
13072
13073        // writer
13074        synchronized (mPackages) {
13075            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13076
13077            // Propagate the permissions state as we do not want to drop on the floor
13078            // runtime permissions. The update permissions method below will take
13079            // care of removing obsolete permissions and grant install permissions.
13080            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13081            updatePermissionsLPw(newPkg.packageName, newPkg,
13082                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13083
13084            if (applyUserRestrictions) {
13085                if (DEBUG_REMOVE) {
13086                    Slog.d(TAG, "Propagating install state across reinstall");
13087                }
13088                for (int i = 0; i < allUserHandles.length; i++) {
13089                    if (DEBUG_REMOVE) {
13090                        Slog.d(TAG, "    user " + allUserHandles[i]
13091                                + " => " + perUserInstalled[i]);
13092                    }
13093                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13094
13095                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13096                }
13097                // Regardless of writeSettings we need to ensure that this restriction
13098                // state propagation is persisted
13099                mSettings.writeAllUsersPackageRestrictionsLPr();
13100            }
13101            // can downgrade to reader here
13102            if (writeSettings) {
13103                mSettings.writeLPr();
13104            }
13105        }
13106        return true;
13107    }
13108
13109    private boolean deleteInstalledPackageLI(PackageSetting ps,
13110            boolean deleteCodeAndResources, int flags,
13111            int[] allUserHandles, boolean[] perUserInstalled,
13112            PackageRemovedInfo outInfo, boolean writeSettings) {
13113        if (outInfo != null) {
13114            outInfo.uid = ps.appId;
13115        }
13116
13117        // Delete package data from internal structures and also remove data if flag is set
13118        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13119
13120        // Delete application code and resources
13121        if (deleteCodeAndResources && (outInfo != null)) {
13122            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13123                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13124            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13125        }
13126        return true;
13127    }
13128
13129    @Override
13130    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13131            int userId) {
13132        mContext.enforceCallingOrSelfPermission(
13133                android.Manifest.permission.DELETE_PACKAGES, null);
13134        synchronized (mPackages) {
13135            PackageSetting ps = mSettings.mPackages.get(packageName);
13136            if (ps == null) {
13137                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13138                return false;
13139            }
13140            if (!ps.getInstalled(userId)) {
13141                // Can't block uninstall for an app that is not installed or enabled.
13142                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13143                return false;
13144            }
13145            ps.setBlockUninstall(blockUninstall, userId);
13146            mSettings.writePackageRestrictionsLPr(userId);
13147        }
13148        return true;
13149    }
13150
13151    @Override
13152    public boolean getBlockUninstallForUser(String packageName, int userId) {
13153        synchronized (mPackages) {
13154            PackageSetting ps = mSettings.mPackages.get(packageName);
13155            if (ps == null) {
13156                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13157                return false;
13158            }
13159            return ps.getBlockUninstall(userId);
13160        }
13161    }
13162
13163    /*
13164     * This method handles package deletion in general
13165     */
13166    private boolean deletePackageLI(String packageName, UserHandle user,
13167            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13168            int flags, PackageRemovedInfo outInfo,
13169            boolean writeSettings) {
13170        if (packageName == null) {
13171            Slog.w(TAG, "Attempt to delete null packageName.");
13172            return false;
13173        }
13174        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13175        PackageSetting ps;
13176        boolean dataOnly = false;
13177        int removeUser = -1;
13178        int appId = -1;
13179        synchronized (mPackages) {
13180            ps = mSettings.mPackages.get(packageName);
13181            if (ps == null) {
13182                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13183                return false;
13184            }
13185            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13186                    && user.getIdentifier() != UserHandle.USER_ALL) {
13187                // The caller is asking that the package only be deleted for a single
13188                // user.  To do this, we just mark its uninstalled state and delete
13189                // its data.  If this is a system app, we only allow this to happen if
13190                // they have set the special DELETE_SYSTEM_APP which requests different
13191                // semantics than normal for uninstalling system apps.
13192                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13193                final int userId = user.getIdentifier();
13194                ps.setUserState(userId,
13195                        COMPONENT_ENABLED_STATE_DEFAULT,
13196                        false, //installed
13197                        true,  //stopped
13198                        true,  //notLaunched
13199                        false, //hidden
13200                        null, null, null,
13201                        false, // blockUninstall
13202                        ps.readUserState(userId).domainVerificationStatus, 0);
13203                if (!isSystemApp(ps)) {
13204                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13205                        // Other user still have this package installed, so all
13206                        // we need to do is clear this user's data and save that
13207                        // it is uninstalled.
13208                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13209                        removeUser = user.getIdentifier();
13210                        appId = ps.appId;
13211                        scheduleWritePackageRestrictionsLocked(removeUser);
13212                    } else {
13213                        // We need to set it back to 'installed' so the uninstall
13214                        // broadcasts will be sent correctly.
13215                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13216                        ps.setInstalled(true, user.getIdentifier());
13217                    }
13218                } else {
13219                    // This is a system app, so we assume that the
13220                    // other users still have this package installed, so all
13221                    // we need to do is clear this user's data and save that
13222                    // it is uninstalled.
13223                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13224                    removeUser = user.getIdentifier();
13225                    appId = ps.appId;
13226                    scheduleWritePackageRestrictionsLocked(removeUser);
13227                }
13228            }
13229        }
13230
13231        if (removeUser >= 0) {
13232            // From above, we determined that we are deleting this only
13233            // for a single user.  Continue the work here.
13234            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13235            if (outInfo != null) {
13236                outInfo.removedPackage = packageName;
13237                outInfo.removedAppId = appId;
13238                outInfo.removedUsers = new int[] {removeUser};
13239            }
13240            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13241            removeKeystoreDataIfNeeded(removeUser, appId);
13242            schedulePackageCleaning(packageName, removeUser, false);
13243            synchronized (mPackages) {
13244                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13245                    scheduleWritePackageRestrictionsLocked(removeUser);
13246                }
13247                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13248            }
13249            return true;
13250        }
13251
13252        if (dataOnly) {
13253            // Delete application data first
13254            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13255            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13256            return true;
13257        }
13258
13259        boolean ret = false;
13260        if (isSystemApp(ps)) {
13261            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13262            // When an updated system application is deleted we delete the existing resources as well and
13263            // fall back to existing code in system partition
13264            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13265                    flags, outInfo, writeSettings);
13266        } else {
13267            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13268            // Kill application pre-emptively especially for apps on sd.
13269            killApplication(packageName, ps.appId, "uninstall pkg");
13270            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13271                    allUserHandles, perUserInstalled,
13272                    outInfo, writeSettings);
13273        }
13274
13275        return ret;
13276    }
13277
13278    private final class ClearStorageConnection implements ServiceConnection {
13279        IMediaContainerService mContainerService;
13280
13281        @Override
13282        public void onServiceConnected(ComponentName name, IBinder service) {
13283            synchronized (this) {
13284                mContainerService = IMediaContainerService.Stub.asInterface(service);
13285                notifyAll();
13286            }
13287        }
13288
13289        @Override
13290        public void onServiceDisconnected(ComponentName name) {
13291        }
13292    }
13293
13294    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13295        final boolean mounted;
13296        if (Environment.isExternalStorageEmulated()) {
13297            mounted = true;
13298        } else {
13299            final String status = Environment.getExternalStorageState();
13300
13301            mounted = status.equals(Environment.MEDIA_MOUNTED)
13302                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13303        }
13304
13305        if (!mounted) {
13306            return;
13307        }
13308
13309        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13310        int[] users;
13311        if (userId == UserHandle.USER_ALL) {
13312            users = sUserManager.getUserIds();
13313        } else {
13314            users = new int[] { userId };
13315        }
13316        final ClearStorageConnection conn = new ClearStorageConnection();
13317        if (mContext.bindServiceAsUser(
13318                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13319            try {
13320                for (int curUser : users) {
13321                    long timeout = SystemClock.uptimeMillis() + 5000;
13322                    synchronized (conn) {
13323                        long now = SystemClock.uptimeMillis();
13324                        while (conn.mContainerService == null && now < timeout) {
13325                            try {
13326                                conn.wait(timeout - now);
13327                            } catch (InterruptedException e) {
13328                            }
13329                        }
13330                    }
13331                    if (conn.mContainerService == null) {
13332                        return;
13333                    }
13334
13335                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13336                    clearDirectory(conn.mContainerService,
13337                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13338                    if (allData) {
13339                        clearDirectory(conn.mContainerService,
13340                                userEnv.buildExternalStorageAppDataDirs(packageName));
13341                        clearDirectory(conn.mContainerService,
13342                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13343                    }
13344                }
13345            } finally {
13346                mContext.unbindService(conn);
13347            }
13348        }
13349    }
13350
13351    @Override
13352    public void clearApplicationUserData(final String packageName,
13353            final IPackageDataObserver observer, final int userId) {
13354        mContext.enforceCallingOrSelfPermission(
13355                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13356        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13357        // Queue up an async operation since the package deletion may take a little while.
13358        mHandler.post(new Runnable() {
13359            public void run() {
13360                mHandler.removeCallbacks(this);
13361                final boolean succeeded;
13362                synchronized (mInstallLock) {
13363                    succeeded = clearApplicationUserDataLI(packageName, userId);
13364                }
13365                clearExternalStorageDataSync(packageName, userId, true);
13366                if (succeeded) {
13367                    // invoke DeviceStorageMonitor's update method to clear any notifications
13368                    DeviceStorageMonitorInternal
13369                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13370                    if (dsm != null) {
13371                        dsm.checkMemory();
13372                    }
13373                }
13374                if(observer != null) {
13375                    try {
13376                        observer.onRemoveCompleted(packageName, succeeded);
13377                    } catch (RemoteException e) {
13378                        Log.i(TAG, "Observer no longer exists.");
13379                    }
13380                } //end if observer
13381            } //end run
13382        });
13383    }
13384
13385    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13386        if (packageName == null) {
13387            Slog.w(TAG, "Attempt to delete null packageName.");
13388            return false;
13389        }
13390
13391        // Try finding details about the requested package
13392        PackageParser.Package pkg;
13393        synchronized (mPackages) {
13394            pkg = mPackages.get(packageName);
13395            if (pkg == null) {
13396                final PackageSetting ps = mSettings.mPackages.get(packageName);
13397                if (ps != null) {
13398                    pkg = ps.pkg;
13399                }
13400            }
13401
13402            if (pkg == null) {
13403                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13404                return false;
13405            }
13406
13407            PackageSetting ps = (PackageSetting) pkg.mExtras;
13408            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13409        }
13410
13411        // Always delete data directories for package, even if we found no other
13412        // record of app. This helps users recover from UID mismatches without
13413        // resorting to a full data wipe.
13414        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13415        if (retCode < 0) {
13416            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13417            return false;
13418        }
13419
13420        final int appId = pkg.applicationInfo.uid;
13421        removeKeystoreDataIfNeeded(userId, appId);
13422
13423        // Create a native library symlink only if we have native libraries
13424        // and if the native libraries are 32 bit libraries. We do not provide
13425        // this symlink for 64 bit libraries.
13426        if (pkg.applicationInfo.primaryCpuAbi != null &&
13427                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13428            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13429            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13430                    nativeLibPath, userId) < 0) {
13431                Slog.w(TAG, "Failed linking native library dir");
13432                return false;
13433            }
13434        }
13435
13436        return true;
13437    }
13438
13439    /**
13440     * Reverts user permission state changes (permissions and flags) in
13441     * all packages for a given user.
13442     *
13443     * @param userId The device user for which to do a reset.
13444     */
13445    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13446        final int packageCount = mPackages.size();
13447        for (int i = 0; i < packageCount; i++) {
13448            PackageParser.Package pkg = mPackages.valueAt(i);
13449            PackageSetting ps = (PackageSetting) pkg.mExtras;
13450            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13451        }
13452    }
13453
13454    /**
13455     * Reverts user permission state changes (permissions and flags).
13456     *
13457     * @param ps The package for which to reset.
13458     * @param userId The device user for which to do a reset.
13459     */
13460    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13461            final PackageSetting ps, final int userId) {
13462        if (ps.pkg == null) {
13463            return;
13464        }
13465
13466        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13467                | FLAG_PERMISSION_USER_FIXED
13468                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13469
13470        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13471                | FLAG_PERMISSION_POLICY_FIXED;
13472
13473        boolean writeInstallPermissions = false;
13474        boolean writeRuntimePermissions = false;
13475
13476        final int permissionCount = ps.pkg.requestedPermissions.size();
13477        for (int i = 0; i < permissionCount; i++) {
13478            String permission = ps.pkg.requestedPermissions.get(i);
13479
13480            BasePermission bp = mSettings.mPermissions.get(permission);
13481            if (bp == null) {
13482                continue;
13483            }
13484
13485            // If shared user we just reset the state to which only this app contributed.
13486            if (ps.sharedUser != null) {
13487                boolean used = false;
13488                final int packageCount = ps.sharedUser.packages.size();
13489                for (int j = 0; j < packageCount; j++) {
13490                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13491                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13492                            && pkg.pkg.requestedPermissions.contains(permission)) {
13493                        used = true;
13494                        break;
13495                    }
13496                }
13497                if (used) {
13498                    continue;
13499                }
13500            }
13501
13502            PermissionsState permissionsState = ps.getPermissionsState();
13503
13504            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13505
13506            // Always clear the user settable flags.
13507            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13508                    bp.name) != null;
13509            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13510                if (hasInstallState) {
13511                    writeInstallPermissions = true;
13512                } else {
13513                    writeRuntimePermissions = true;
13514                }
13515            }
13516
13517            // Below is only runtime permission handling.
13518            if (!bp.isRuntime()) {
13519                continue;
13520            }
13521
13522            // Never clobber system or policy.
13523            if ((oldFlags & policyOrSystemFlags) != 0) {
13524                continue;
13525            }
13526
13527            // If this permission was granted by default, make sure it is.
13528            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13529                if (permissionsState.grantRuntimePermission(bp, userId)
13530                        != PERMISSION_OPERATION_FAILURE) {
13531                    writeRuntimePermissions = true;
13532                }
13533            } else {
13534                // Otherwise, reset the permission.
13535                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13536                switch (revokeResult) {
13537                    case PERMISSION_OPERATION_SUCCESS: {
13538                        writeRuntimePermissions = true;
13539                    } break;
13540
13541                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13542                        writeRuntimePermissions = true;
13543                        final int appId = ps.appId;
13544                        mHandler.post(new Runnable() {
13545                            @Override
13546                            public void run() {
13547                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13548                            }
13549                        });
13550                    } break;
13551                }
13552            }
13553        }
13554
13555        // Synchronously write as we are taking permissions away.
13556        if (writeRuntimePermissions) {
13557            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13558        }
13559
13560        // Synchronously write as we are taking permissions away.
13561        if (writeInstallPermissions) {
13562            mSettings.writeLPr();
13563        }
13564    }
13565
13566    /**
13567     * Remove entries from the keystore daemon. Will only remove it if the
13568     * {@code appId} is valid.
13569     */
13570    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13571        if (appId < 0) {
13572            return;
13573        }
13574
13575        final KeyStore keyStore = KeyStore.getInstance();
13576        if (keyStore != null) {
13577            if (userId == UserHandle.USER_ALL) {
13578                for (final int individual : sUserManager.getUserIds()) {
13579                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13580                }
13581            } else {
13582                keyStore.clearUid(UserHandle.getUid(userId, appId));
13583            }
13584        } else {
13585            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13586        }
13587    }
13588
13589    @Override
13590    public void deleteApplicationCacheFiles(final String packageName,
13591            final IPackageDataObserver observer) {
13592        mContext.enforceCallingOrSelfPermission(
13593                android.Manifest.permission.DELETE_CACHE_FILES, null);
13594        // Queue up an async operation since the package deletion may take a little while.
13595        final int userId = UserHandle.getCallingUserId();
13596        mHandler.post(new Runnable() {
13597            public void run() {
13598                mHandler.removeCallbacks(this);
13599                final boolean succeded;
13600                synchronized (mInstallLock) {
13601                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13602                }
13603                clearExternalStorageDataSync(packageName, userId, false);
13604                if (observer != null) {
13605                    try {
13606                        observer.onRemoveCompleted(packageName, succeded);
13607                    } catch (RemoteException e) {
13608                        Log.i(TAG, "Observer no longer exists.");
13609                    }
13610                } //end if observer
13611            } //end run
13612        });
13613    }
13614
13615    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13616        if (packageName == null) {
13617            Slog.w(TAG, "Attempt to delete null packageName.");
13618            return false;
13619        }
13620        PackageParser.Package p;
13621        synchronized (mPackages) {
13622            p = mPackages.get(packageName);
13623        }
13624        if (p == null) {
13625            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13626            return false;
13627        }
13628        final ApplicationInfo applicationInfo = p.applicationInfo;
13629        if (applicationInfo == null) {
13630            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13631            return false;
13632        }
13633        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13634        if (retCode < 0) {
13635            Slog.w(TAG, "Couldn't remove cache files for package: "
13636                       + packageName + " u" + userId);
13637            return false;
13638        }
13639        return true;
13640    }
13641
13642    @Override
13643    public void getPackageSizeInfo(final String packageName, int userHandle,
13644            final IPackageStatsObserver observer) {
13645        mContext.enforceCallingOrSelfPermission(
13646                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13647        if (packageName == null) {
13648            throw new IllegalArgumentException("Attempt to get size of null packageName");
13649        }
13650
13651        PackageStats stats = new PackageStats(packageName, userHandle);
13652
13653        /*
13654         * Queue up an async operation since the package measurement may take a
13655         * little while.
13656         */
13657        Message msg = mHandler.obtainMessage(INIT_COPY);
13658        msg.obj = new MeasureParams(stats, observer);
13659        mHandler.sendMessage(msg);
13660    }
13661
13662    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13663            PackageStats pStats) {
13664        if (packageName == null) {
13665            Slog.w(TAG, "Attempt to get size of null packageName.");
13666            return false;
13667        }
13668        PackageParser.Package p;
13669        boolean dataOnly = false;
13670        String libDirRoot = null;
13671        String asecPath = null;
13672        PackageSetting ps = null;
13673        synchronized (mPackages) {
13674            p = mPackages.get(packageName);
13675            ps = mSettings.mPackages.get(packageName);
13676            if(p == null) {
13677                dataOnly = true;
13678                if((ps == null) || (ps.pkg == null)) {
13679                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13680                    return false;
13681                }
13682                p = ps.pkg;
13683            }
13684            if (ps != null) {
13685                libDirRoot = ps.legacyNativeLibraryPathString;
13686            }
13687            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13688                final long token = Binder.clearCallingIdentity();
13689                try {
13690                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13691                    if (secureContainerId != null) {
13692                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13693                    }
13694                } finally {
13695                    Binder.restoreCallingIdentity(token);
13696                }
13697            }
13698        }
13699        String publicSrcDir = null;
13700        if(!dataOnly) {
13701            final ApplicationInfo applicationInfo = p.applicationInfo;
13702            if (applicationInfo == null) {
13703                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13704                return false;
13705            }
13706            if (p.isForwardLocked()) {
13707                publicSrcDir = applicationInfo.getBaseResourcePath();
13708            }
13709        }
13710        // TODO: extend to measure size of split APKs
13711        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13712        // not just the first level.
13713        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13714        // just the primary.
13715        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13716
13717        String apkPath;
13718        File packageDir = new File(p.codePath);
13719
13720        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13721            apkPath = packageDir.getAbsolutePath();
13722            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13723            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13724                libDirRoot = null;
13725            }
13726        } else {
13727            apkPath = p.baseCodePath;
13728        }
13729
13730        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13731                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13732        if (res < 0) {
13733            return false;
13734        }
13735
13736        // Fix-up for forward-locked applications in ASEC containers.
13737        if (!isExternal(p)) {
13738            pStats.codeSize += pStats.externalCodeSize;
13739            pStats.externalCodeSize = 0L;
13740        }
13741
13742        return true;
13743    }
13744
13745
13746    @Override
13747    public void addPackageToPreferred(String packageName) {
13748        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13749    }
13750
13751    @Override
13752    public void removePackageFromPreferred(String packageName) {
13753        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13754    }
13755
13756    @Override
13757    public List<PackageInfo> getPreferredPackages(int flags) {
13758        return new ArrayList<PackageInfo>();
13759    }
13760
13761    private int getUidTargetSdkVersionLockedLPr(int uid) {
13762        Object obj = mSettings.getUserIdLPr(uid);
13763        if (obj instanceof SharedUserSetting) {
13764            final SharedUserSetting sus = (SharedUserSetting) obj;
13765            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13766            final Iterator<PackageSetting> it = sus.packages.iterator();
13767            while (it.hasNext()) {
13768                final PackageSetting ps = it.next();
13769                if (ps.pkg != null) {
13770                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13771                    if (v < vers) vers = v;
13772                }
13773            }
13774            return vers;
13775        } else if (obj instanceof PackageSetting) {
13776            final PackageSetting ps = (PackageSetting) obj;
13777            if (ps.pkg != null) {
13778                return ps.pkg.applicationInfo.targetSdkVersion;
13779            }
13780        }
13781        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13782    }
13783
13784    @Override
13785    public void addPreferredActivity(IntentFilter filter, int match,
13786            ComponentName[] set, ComponentName activity, int userId) {
13787        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13788                "Adding preferred");
13789    }
13790
13791    private void addPreferredActivityInternal(IntentFilter filter, int match,
13792            ComponentName[] set, ComponentName activity, boolean always, int userId,
13793            String opname) {
13794        // writer
13795        int callingUid = Binder.getCallingUid();
13796        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13797        if (filter.countActions() == 0) {
13798            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13799            return;
13800        }
13801        synchronized (mPackages) {
13802            if (mContext.checkCallingOrSelfPermission(
13803                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13804                    != PackageManager.PERMISSION_GRANTED) {
13805                if (getUidTargetSdkVersionLockedLPr(callingUid)
13806                        < Build.VERSION_CODES.FROYO) {
13807                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13808                            + callingUid);
13809                    return;
13810                }
13811                mContext.enforceCallingOrSelfPermission(
13812                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13813            }
13814
13815            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13816            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13817                    + userId + ":");
13818            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13819            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13820            scheduleWritePackageRestrictionsLocked(userId);
13821        }
13822    }
13823
13824    @Override
13825    public void replacePreferredActivity(IntentFilter filter, int match,
13826            ComponentName[] set, ComponentName activity, int userId) {
13827        if (filter.countActions() != 1) {
13828            throw new IllegalArgumentException(
13829                    "replacePreferredActivity expects filter to have only 1 action.");
13830        }
13831        if (filter.countDataAuthorities() != 0
13832                || filter.countDataPaths() != 0
13833                || filter.countDataSchemes() > 1
13834                || filter.countDataTypes() != 0) {
13835            throw new IllegalArgumentException(
13836                    "replacePreferredActivity expects filter to have no data authorities, " +
13837                    "paths, or types; and at most one scheme.");
13838        }
13839
13840        final int callingUid = Binder.getCallingUid();
13841        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13842        synchronized (mPackages) {
13843            if (mContext.checkCallingOrSelfPermission(
13844                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13845                    != PackageManager.PERMISSION_GRANTED) {
13846                if (getUidTargetSdkVersionLockedLPr(callingUid)
13847                        < Build.VERSION_CODES.FROYO) {
13848                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13849                            + Binder.getCallingUid());
13850                    return;
13851                }
13852                mContext.enforceCallingOrSelfPermission(
13853                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13854            }
13855
13856            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13857            if (pir != null) {
13858                // Get all of the existing entries that exactly match this filter.
13859                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13860                if (existing != null && existing.size() == 1) {
13861                    PreferredActivity cur = existing.get(0);
13862                    if (DEBUG_PREFERRED) {
13863                        Slog.i(TAG, "Checking replace of preferred:");
13864                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13865                        if (!cur.mPref.mAlways) {
13866                            Slog.i(TAG, "  -- CUR; not mAlways!");
13867                        } else {
13868                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13869                            Slog.i(TAG, "  -- CUR: mSet="
13870                                    + Arrays.toString(cur.mPref.mSetComponents));
13871                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13872                            Slog.i(TAG, "  -- NEW: mMatch="
13873                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13874                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13875                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13876                        }
13877                    }
13878                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13879                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13880                            && cur.mPref.sameSet(set)) {
13881                        // Setting the preferred activity to what it happens to be already
13882                        if (DEBUG_PREFERRED) {
13883                            Slog.i(TAG, "Replacing with same preferred activity "
13884                                    + cur.mPref.mShortComponent + " for user "
13885                                    + userId + ":");
13886                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13887                        }
13888                        return;
13889                    }
13890                }
13891
13892                if (existing != null) {
13893                    if (DEBUG_PREFERRED) {
13894                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13895                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13896                    }
13897                    for (int i = 0; i < existing.size(); i++) {
13898                        PreferredActivity pa = existing.get(i);
13899                        if (DEBUG_PREFERRED) {
13900                            Slog.i(TAG, "Removing existing preferred activity "
13901                                    + pa.mPref.mComponent + ":");
13902                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13903                        }
13904                        pir.removeFilter(pa);
13905                    }
13906                }
13907            }
13908            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13909                    "Replacing preferred");
13910        }
13911    }
13912
13913    @Override
13914    public void clearPackagePreferredActivities(String packageName) {
13915        final int uid = Binder.getCallingUid();
13916        // writer
13917        synchronized (mPackages) {
13918            PackageParser.Package pkg = mPackages.get(packageName);
13919            if (pkg == null || pkg.applicationInfo.uid != uid) {
13920                if (mContext.checkCallingOrSelfPermission(
13921                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13922                        != PackageManager.PERMISSION_GRANTED) {
13923                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13924                            < Build.VERSION_CODES.FROYO) {
13925                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13926                                + Binder.getCallingUid());
13927                        return;
13928                    }
13929                    mContext.enforceCallingOrSelfPermission(
13930                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13931                }
13932            }
13933
13934            int user = UserHandle.getCallingUserId();
13935            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13936                scheduleWritePackageRestrictionsLocked(user);
13937            }
13938        }
13939    }
13940
13941    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13942    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13943        ArrayList<PreferredActivity> removed = null;
13944        boolean changed = false;
13945        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13946            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13947            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13948            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13949                continue;
13950            }
13951            Iterator<PreferredActivity> it = pir.filterIterator();
13952            while (it.hasNext()) {
13953                PreferredActivity pa = it.next();
13954                // Mark entry for removal only if it matches the package name
13955                // and the entry is of type "always".
13956                if (packageName == null ||
13957                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13958                                && pa.mPref.mAlways)) {
13959                    if (removed == null) {
13960                        removed = new ArrayList<PreferredActivity>();
13961                    }
13962                    removed.add(pa);
13963                }
13964            }
13965            if (removed != null) {
13966                for (int j=0; j<removed.size(); j++) {
13967                    PreferredActivity pa = removed.get(j);
13968                    pir.removeFilter(pa);
13969                }
13970                changed = true;
13971            }
13972        }
13973        return changed;
13974    }
13975
13976    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13977    private void clearIntentFilterVerificationsLPw(int userId) {
13978        final int packageCount = mPackages.size();
13979        for (int i = 0; i < packageCount; i++) {
13980            PackageParser.Package pkg = mPackages.valueAt(i);
13981            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13982        }
13983    }
13984
13985    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13986    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13987        if (userId == UserHandle.USER_ALL) {
13988            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13989                    sUserManager.getUserIds())) {
13990                for (int oneUserId : sUserManager.getUserIds()) {
13991                    scheduleWritePackageRestrictionsLocked(oneUserId);
13992                }
13993            }
13994        } else {
13995            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13996                scheduleWritePackageRestrictionsLocked(userId);
13997            }
13998        }
13999    }
14000
14001    void clearDefaultBrowserIfNeeded(String packageName) {
14002        for (int oneUserId : sUserManager.getUserIds()) {
14003            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14004            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14005            if (packageName.equals(defaultBrowserPackageName)) {
14006                setDefaultBrowserPackageName(null, oneUserId);
14007            }
14008        }
14009    }
14010
14011    @Override
14012    public void resetApplicationPreferences(int userId) {
14013        mContext.enforceCallingOrSelfPermission(
14014                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14015        // writer
14016        synchronized (mPackages) {
14017            final long identity = Binder.clearCallingIdentity();
14018            try {
14019                clearPackagePreferredActivitiesLPw(null, userId);
14020                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14021                // TODO: We have to reset the default SMS and Phone. This requires
14022                // significant refactoring to keep all default apps in the package
14023                // manager (cleaner but more work) or have the services provide
14024                // callbacks to the package manager to request a default app reset.
14025                applyFactoryDefaultBrowserLPw(userId);
14026                clearIntentFilterVerificationsLPw(userId);
14027                primeDomainVerificationsLPw(userId);
14028                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14029                scheduleWritePackageRestrictionsLocked(userId);
14030            } finally {
14031                Binder.restoreCallingIdentity(identity);
14032            }
14033        }
14034    }
14035
14036    @Override
14037    public int getPreferredActivities(List<IntentFilter> outFilters,
14038            List<ComponentName> outActivities, String packageName) {
14039
14040        int num = 0;
14041        final int userId = UserHandle.getCallingUserId();
14042        // reader
14043        synchronized (mPackages) {
14044            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14045            if (pir != null) {
14046                final Iterator<PreferredActivity> it = pir.filterIterator();
14047                while (it.hasNext()) {
14048                    final PreferredActivity pa = it.next();
14049                    if (packageName == null
14050                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14051                                    && pa.mPref.mAlways)) {
14052                        if (outFilters != null) {
14053                            outFilters.add(new IntentFilter(pa));
14054                        }
14055                        if (outActivities != null) {
14056                            outActivities.add(pa.mPref.mComponent);
14057                        }
14058                    }
14059                }
14060            }
14061        }
14062
14063        return num;
14064    }
14065
14066    @Override
14067    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14068            int userId) {
14069        int callingUid = Binder.getCallingUid();
14070        if (callingUid != Process.SYSTEM_UID) {
14071            throw new SecurityException(
14072                    "addPersistentPreferredActivity can only be run by the system");
14073        }
14074        if (filter.countActions() == 0) {
14075            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14076            return;
14077        }
14078        synchronized (mPackages) {
14079            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14080                    " :");
14081            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14082            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14083                    new PersistentPreferredActivity(filter, activity));
14084            scheduleWritePackageRestrictionsLocked(userId);
14085        }
14086    }
14087
14088    @Override
14089    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14090        int callingUid = Binder.getCallingUid();
14091        if (callingUid != Process.SYSTEM_UID) {
14092            throw new SecurityException(
14093                    "clearPackagePersistentPreferredActivities can only be run by the system");
14094        }
14095        ArrayList<PersistentPreferredActivity> removed = null;
14096        boolean changed = false;
14097        synchronized (mPackages) {
14098            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14099                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14100                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14101                        .valueAt(i);
14102                if (userId != thisUserId) {
14103                    continue;
14104                }
14105                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14106                while (it.hasNext()) {
14107                    PersistentPreferredActivity ppa = it.next();
14108                    // Mark entry for removal only if it matches the package name.
14109                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14110                        if (removed == null) {
14111                            removed = new ArrayList<PersistentPreferredActivity>();
14112                        }
14113                        removed.add(ppa);
14114                    }
14115                }
14116                if (removed != null) {
14117                    for (int j=0; j<removed.size(); j++) {
14118                        PersistentPreferredActivity ppa = removed.get(j);
14119                        ppir.removeFilter(ppa);
14120                    }
14121                    changed = true;
14122                }
14123            }
14124
14125            if (changed) {
14126                scheduleWritePackageRestrictionsLocked(userId);
14127            }
14128        }
14129    }
14130
14131    /**
14132     * Common machinery for picking apart a restored XML blob and passing
14133     * it to a caller-supplied functor to be applied to the running system.
14134     */
14135    private void restoreFromXml(XmlPullParser parser, int userId,
14136            String expectedStartTag, BlobXmlRestorer functor)
14137            throws IOException, XmlPullParserException {
14138        int type;
14139        while ((type = parser.next()) != XmlPullParser.START_TAG
14140                && type != XmlPullParser.END_DOCUMENT) {
14141        }
14142        if (type != XmlPullParser.START_TAG) {
14143            // oops didn't find a start tag?!
14144            if (DEBUG_BACKUP) {
14145                Slog.e(TAG, "Didn't find start tag during restore");
14146            }
14147            return;
14148        }
14149
14150        // this is supposed to be TAG_PREFERRED_BACKUP
14151        if (!expectedStartTag.equals(parser.getName())) {
14152            if (DEBUG_BACKUP) {
14153                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14154            }
14155            return;
14156        }
14157
14158        // skip interfering stuff, then we're aligned with the backing implementation
14159        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14160        functor.apply(parser, userId);
14161    }
14162
14163    private interface BlobXmlRestorer {
14164        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14165    }
14166
14167    /**
14168     * Non-Binder method, support for the backup/restore mechanism: write the
14169     * full set of preferred activities in its canonical XML format.  Returns the
14170     * XML output as a byte array, or null if there is none.
14171     */
14172    @Override
14173    public byte[] getPreferredActivityBackup(int userId) {
14174        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14175            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14176        }
14177
14178        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14179        try {
14180            final XmlSerializer serializer = new FastXmlSerializer();
14181            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14182            serializer.startDocument(null, true);
14183            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14184
14185            synchronized (mPackages) {
14186                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14187            }
14188
14189            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14190            serializer.endDocument();
14191            serializer.flush();
14192        } catch (Exception e) {
14193            if (DEBUG_BACKUP) {
14194                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14195            }
14196            return null;
14197        }
14198
14199        return dataStream.toByteArray();
14200    }
14201
14202    @Override
14203    public void restorePreferredActivities(byte[] backup, int userId) {
14204        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14205            throw new SecurityException("Only the system may call restorePreferredActivities()");
14206        }
14207
14208        try {
14209            final XmlPullParser parser = Xml.newPullParser();
14210            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14211            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14212                    new BlobXmlRestorer() {
14213                        @Override
14214                        public void apply(XmlPullParser parser, int userId)
14215                                throws XmlPullParserException, IOException {
14216                            synchronized (mPackages) {
14217                                mSettings.readPreferredActivitiesLPw(parser, userId);
14218                            }
14219                        }
14220                    } );
14221        } catch (Exception e) {
14222            if (DEBUG_BACKUP) {
14223                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14224            }
14225        }
14226    }
14227
14228    /**
14229     * Non-Binder method, support for the backup/restore mechanism: write the
14230     * default browser (etc) settings in its canonical XML format.  Returns the default
14231     * browser XML representation as a byte array, or null if there is none.
14232     */
14233    @Override
14234    public byte[] getDefaultAppsBackup(int userId) {
14235        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14236            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14237        }
14238
14239        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14240        try {
14241            final XmlSerializer serializer = new FastXmlSerializer();
14242            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14243            serializer.startDocument(null, true);
14244            serializer.startTag(null, TAG_DEFAULT_APPS);
14245
14246            synchronized (mPackages) {
14247                mSettings.writeDefaultAppsLPr(serializer, userId);
14248            }
14249
14250            serializer.endTag(null, TAG_DEFAULT_APPS);
14251            serializer.endDocument();
14252            serializer.flush();
14253        } catch (Exception e) {
14254            if (DEBUG_BACKUP) {
14255                Slog.e(TAG, "Unable to write default apps for backup", e);
14256            }
14257            return null;
14258        }
14259
14260        return dataStream.toByteArray();
14261    }
14262
14263    @Override
14264    public void restoreDefaultApps(byte[] backup, int userId) {
14265        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14266            throw new SecurityException("Only the system may call restoreDefaultApps()");
14267        }
14268
14269        try {
14270            final XmlPullParser parser = Xml.newPullParser();
14271            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14272            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14273                    new BlobXmlRestorer() {
14274                        @Override
14275                        public void apply(XmlPullParser parser, int userId)
14276                                throws XmlPullParserException, IOException {
14277                            synchronized (mPackages) {
14278                                mSettings.readDefaultAppsLPw(parser, userId);
14279                            }
14280                        }
14281                    } );
14282        } catch (Exception e) {
14283            if (DEBUG_BACKUP) {
14284                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14285            }
14286        }
14287    }
14288
14289    @Override
14290    public byte[] getIntentFilterVerificationBackup(int userId) {
14291        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14292            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14293        }
14294
14295        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14296        try {
14297            final XmlSerializer serializer = new FastXmlSerializer();
14298            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14299            serializer.startDocument(null, true);
14300            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14301
14302            synchronized (mPackages) {
14303                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14304            }
14305
14306            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14307            serializer.endDocument();
14308            serializer.flush();
14309        } catch (Exception e) {
14310            if (DEBUG_BACKUP) {
14311                Slog.e(TAG, "Unable to write default apps for backup", e);
14312            }
14313            return null;
14314        }
14315
14316        return dataStream.toByteArray();
14317    }
14318
14319    @Override
14320    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14321        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14322            throw new SecurityException("Only the system may call restorePreferredActivities()");
14323        }
14324
14325        try {
14326            final XmlPullParser parser = Xml.newPullParser();
14327            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14328            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14329                    new BlobXmlRestorer() {
14330                        @Override
14331                        public void apply(XmlPullParser parser, int userId)
14332                                throws XmlPullParserException, IOException {
14333                            synchronized (mPackages) {
14334                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14335                                mSettings.writeLPr();
14336                            }
14337                        }
14338                    } );
14339        } catch (Exception e) {
14340            if (DEBUG_BACKUP) {
14341                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14342            }
14343        }
14344    }
14345
14346    @Override
14347    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14348            int sourceUserId, int targetUserId, int flags) {
14349        mContext.enforceCallingOrSelfPermission(
14350                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14351        int callingUid = Binder.getCallingUid();
14352        enforceOwnerRights(ownerPackage, callingUid);
14353        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14354        if (intentFilter.countActions() == 0) {
14355            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14356            return;
14357        }
14358        synchronized (mPackages) {
14359            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14360                    ownerPackage, targetUserId, flags);
14361            CrossProfileIntentResolver resolver =
14362                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14363            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14364            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14365            if (existing != null) {
14366                int size = existing.size();
14367                for (int i = 0; i < size; i++) {
14368                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14369                        return;
14370                    }
14371                }
14372            }
14373            resolver.addFilter(newFilter);
14374            scheduleWritePackageRestrictionsLocked(sourceUserId);
14375        }
14376    }
14377
14378    @Override
14379    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14380        mContext.enforceCallingOrSelfPermission(
14381                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14382        int callingUid = Binder.getCallingUid();
14383        enforceOwnerRights(ownerPackage, callingUid);
14384        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14385        synchronized (mPackages) {
14386            CrossProfileIntentResolver resolver =
14387                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14388            ArraySet<CrossProfileIntentFilter> set =
14389                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14390            for (CrossProfileIntentFilter filter : set) {
14391                if (filter.getOwnerPackage().equals(ownerPackage)) {
14392                    resolver.removeFilter(filter);
14393                }
14394            }
14395            scheduleWritePackageRestrictionsLocked(sourceUserId);
14396        }
14397    }
14398
14399    // Enforcing that callingUid is owning pkg on userId
14400    private void enforceOwnerRights(String pkg, int callingUid) {
14401        // The system owns everything.
14402        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14403            return;
14404        }
14405        int callingUserId = UserHandle.getUserId(callingUid);
14406        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14407        if (pi == null) {
14408            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14409                    + callingUserId);
14410        }
14411        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14412            throw new SecurityException("Calling uid " + callingUid
14413                    + " does not own package " + pkg);
14414        }
14415    }
14416
14417    @Override
14418    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14419        Intent intent = new Intent(Intent.ACTION_MAIN);
14420        intent.addCategory(Intent.CATEGORY_HOME);
14421
14422        final int callingUserId = UserHandle.getCallingUserId();
14423        List<ResolveInfo> list = queryIntentActivities(intent, null,
14424                PackageManager.GET_META_DATA, callingUserId);
14425        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14426                true, false, false, callingUserId);
14427
14428        allHomeCandidates.clear();
14429        if (list != null) {
14430            for (ResolveInfo ri : list) {
14431                allHomeCandidates.add(ri);
14432            }
14433        }
14434        return (preferred == null || preferred.activityInfo == null)
14435                ? null
14436                : new ComponentName(preferred.activityInfo.packageName,
14437                        preferred.activityInfo.name);
14438    }
14439
14440    @Override
14441    public void setApplicationEnabledSetting(String appPackageName,
14442            int newState, int flags, int userId, String callingPackage) {
14443        if (!sUserManager.exists(userId)) return;
14444        if (callingPackage == null) {
14445            callingPackage = Integer.toString(Binder.getCallingUid());
14446        }
14447        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14448    }
14449
14450    @Override
14451    public void setComponentEnabledSetting(ComponentName componentName,
14452            int newState, int flags, int userId) {
14453        if (!sUserManager.exists(userId)) return;
14454        setEnabledSetting(componentName.getPackageName(),
14455                componentName.getClassName(), newState, flags, userId, null);
14456    }
14457
14458    private void setEnabledSetting(final String packageName, String className, int newState,
14459            final int flags, int userId, String callingPackage) {
14460        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14461              || newState == COMPONENT_ENABLED_STATE_ENABLED
14462              || newState == COMPONENT_ENABLED_STATE_DISABLED
14463              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14464              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14465            throw new IllegalArgumentException("Invalid new component state: "
14466                    + newState);
14467        }
14468        PackageSetting pkgSetting;
14469        final int uid = Binder.getCallingUid();
14470        final int permission = mContext.checkCallingOrSelfPermission(
14471                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14472        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14473        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14474        boolean sendNow = false;
14475        boolean isApp = (className == null);
14476        String componentName = isApp ? packageName : className;
14477        int packageUid = -1;
14478        ArrayList<String> components;
14479
14480        // writer
14481        synchronized (mPackages) {
14482            pkgSetting = mSettings.mPackages.get(packageName);
14483            if (pkgSetting == null) {
14484                if (className == null) {
14485                    throw new IllegalArgumentException(
14486                            "Unknown package: " + packageName);
14487                }
14488                throw new IllegalArgumentException(
14489                        "Unknown component: " + packageName
14490                        + "/" + className);
14491            }
14492            // Allow root and verify that userId is not being specified by a different user
14493            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14494                throw new SecurityException(
14495                        "Permission Denial: attempt to change component state from pid="
14496                        + Binder.getCallingPid()
14497                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14498            }
14499            if (className == null) {
14500                // We're dealing with an application/package level state change
14501                if (pkgSetting.getEnabled(userId) == newState) {
14502                    // Nothing to do
14503                    return;
14504                }
14505                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14506                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14507                    // Don't care about who enables an app.
14508                    callingPackage = null;
14509                }
14510                pkgSetting.setEnabled(newState, userId, callingPackage);
14511                // pkgSetting.pkg.mSetEnabled = newState;
14512            } else {
14513                // We're dealing with a component level state change
14514                // First, verify that this is a valid class name.
14515                PackageParser.Package pkg = pkgSetting.pkg;
14516                if (pkg == null || !pkg.hasComponentClassName(className)) {
14517                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14518                        throw new IllegalArgumentException("Component class " + className
14519                                + " does not exist in " + packageName);
14520                    } else {
14521                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14522                                + className + " does not exist in " + packageName);
14523                    }
14524                }
14525                switch (newState) {
14526                case COMPONENT_ENABLED_STATE_ENABLED:
14527                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14528                        return;
14529                    }
14530                    break;
14531                case COMPONENT_ENABLED_STATE_DISABLED:
14532                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14533                        return;
14534                    }
14535                    break;
14536                case COMPONENT_ENABLED_STATE_DEFAULT:
14537                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14538                        return;
14539                    }
14540                    break;
14541                default:
14542                    Slog.e(TAG, "Invalid new component state: " + newState);
14543                    return;
14544                }
14545            }
14546            scheduleWritePackageRestrictionsLocked(userId);
14547            components = mPendingBroadcasts.get(userId, packageName);
14548            final boolean newPackage = components == null;
14549            if (newPackage) {
14550                components = new ArrayList<String>();
14551            }
14552            if (!components.contains(componentName)) {
14553                components.add(componentName);
14554            }
14555            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14556                sendNow = true;
14557                // Purge entry from pending broadcast list if another one exists already
14558                // since we are sending one right away.
14559                mPendingBroadcasts.remove(userId, packageName);
14560            } else {
14561                if (newPackage) {
14562                    mPendingBroadcasts.put(userId, packageName, components);
14563                }
14564                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14565                    // Schedule a message
14566                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14567                }
14568            }
14569        }
14570
14571        long callingId = Binder.clearCallingIdentity();
14572        try {
14573            if (sendNow) {
14574                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14575                sendPackageChangedBroadcast(packageName,
14576                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14577            }
14578        } finally {
14579            Binder.restoreCallingIdentity(callingId);
14580        }
14581    }
14582
14583    private void sendPackageChangedBroadcast(String packageName,
14584            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14585        if (DEBUG_INSTALL)
14586            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14587                    + componentNames);
14588        Bundle extras = new Bundle(4);
14589        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14590        String nameList[] = new String[componentNames.size()];
14591        componentNames.toArray(nameList);
14592        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14593        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14594        extras.putInt(Intent.EXTRA_UID, packageUid);
14595        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14596                new int[] {UserHandle.getUserId(packageUid)});
14597    }
14598
14599    @Override
14600    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14601        if (!sUserManager.exists(userId)) return;
14602        final int uid = Binder.getCallingUid();
14603        final int permission = mContext.checkCallingOrSelfPermission(
14604                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14605        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14606        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14607        // writer
14608        synchronized (mPackages) {
14609            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14610                    allowedByPermission, uid, userId)) {
14611                scheduleWritePackageRestrictionsLocked(userId);
14612            }
14613        }
14614    }
14615
14616    @Override
14617    public String getInstallerPackageName(String packageName) {
14618        // reader
14619        synchronized (mPackages) {
14620            return mSettings.getInstallerPackageNameLPr(packageName);
14621        }
14622    }
14623
14624    @Override
14625    public int getApplicationEnabledSetting(String packageName, int userId) {
14626        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14627        int uid = Binder.getCallingUid();
14628        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14629        // reader
14630        synchronized (mPackages) {
14631            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14632        }
14633    }
14634
14635    @Override
14636    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14637        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14638        int uid = Binder.getCallingUid();
14639        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14640        // reader
14641        synchronized (mPackages) {
14642            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14643        }
14644    }
14645
14646    @Override
14647    public void enterSafeMode() {
14648        enforceSystemOrRoot("Only the system can request entering safe mode");
14649
14650        if (!mSystemReady) {
14651            mSafeMode = true;
14652        }
14653    }
14654
14655    @Override
14656    public void systemReady() {
14657        mSystemReady = true;
14658
14659        // Read the compatibilty setting when the system is ready.
14660        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14661                mContext.getContentResolver(),
14662                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14663        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14664        if (DEBUG_SETTINGS) {
14665            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14666        }
14667
14668        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14669
14670        synchronized (mPackages) {
14671            // Verify that all of the preferred activity components actually
14672            // exist.  It is possible for applications to be updated and at
14673            // that point remove a previously declared activity component that
14674            // had been set as a preferred activity.  We try to clean this up
14675            // the next time we encounter that preferred activity, but it is
14676            // possible for the user flow to never be able to return to that
14677            // situation so here we do a sanity check to make sure we haven't
14678            // left any junk around.
14679            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14680            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14681                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14682                removed.clear();
14683                for (PreferredActivity pa : pir.filterSet()) {
14684                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14685                        removed.add(pa);
14686                    }
14687                }
14688                if (removed.size() > 0) {
14689                    for (int r=0; r<removed.size(); r++) {
14690                        PreferredActivity pa = removed.get(r);
14691                        Slog.w(TAG, "Removing dangling preferred activity: "
14692                                + pa.mPref.mComponent);
14693                        pir.removeFilter(pa);
14694                    }
14695                    mSettings.writePackageRestrictionsLPr(
14696                            mSettings.mPreferredActivities.keyAt(i));
14697                }
14698            }
14699
14700            for (int userId : UserManagerService.getInstance().getUserIds()) {
14701                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14702                    grantPermissionsUserIds = ArrayUtils.appendInt(
14703                            grantPermissionsUserIds, userId);
14704                }
14705            }
14706        }
14707        sUserManager.systemReady();
14708
14709        // If we upgraded grant all default permissions before kicking off.
14710        for (int userId : grantPermissionsUserIds) {
14711            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14712        }
14713
14714        // Kick off any messages waiting for system ready
14715        if (mPostSystemReadyMessages != null) {
14716            for (Message msg : mPostSystemReadyMessages) {
14717                msg.sendToTarget();
14718            }
14719            mPostSystemReadyMessages = null;
14720        }
14721
14722        // Watch for external volumes that come and go over time
14723        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14724        storage.registerListener(mStorageListener);
14725
14726        mInstallerService.systemReady();
14727        mPackageDexOptimizer.systemReady();
14728
14729        MountServiceInternal mountServiceInternal = LocalServices.getService(
14730                MountServiceInternal.class);
14731        mountServiceInternal.addExternalStoragePolicy(
14732                new MountServiceInternal.ExternalStorageMountPolicy() {
14733            @Override
14734            public int getMountMode(int uid, String packageName) {
14735                if (Process.isIsolated(uid)) {
14736                    return Zygote.MOUNT_EXTERNAL_NONE;
14737                }
14738                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14739                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14740                }
14741                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14742                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14743                }
14744                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14745                    return Zygote.MOUNT_EXTERNAL_READ;
14746                }
14747                return Zygote.MOUNT_EXTERNAL_WRITE;
14748            }
14749
14750            @Override
14751            public boolean hasExternalStorage(int uid, String packageName) {
14752                return true;
14753            }
14754        });
14755    }
14756
14757    @Override
14758    public boolean isSafeMode() {
14759        return mSafeMode;
14760    }
14761
14762    @Override
14763    public boolean hasSystemUidErrors() {
14764        return mHasSystemUidErrors;
14765    }
14766
14767    static String arrayToString(int[] array) {
14768        StringBuffer buf = new StringBuffer(128);
14769        buf.append('[');
14770        if (array != null) {
14771            for (int i=0; i<array.length; i++) {
14772                if (i > 0) buf.append(", ");
14773                buf.append(array[i]);
14774            }
14775        }
14776        buf.append(']');
14777        return buf.toString();
14778    }
14779
14780    static class DumpState {
14781        public static final int DUMP_LIBS = 1 << 0;
14782        public static final int DUMP_FEATURES = 1 << 1;
14783        public static final int DUMP_RESOLVERS = 1 << 2;
14784        public static final int DUMP_PERMISSIONS = 1 << 3;
14785        public static final int DUMP_PACKAGES = 1 << 4;
14786        public static final int DUMP_SHARED_USERS = 1 << 5;
14787        public static final int DUMP_MESSAGES = 1 << 6;
14788        public static final int DUMP_PROVIDERS = 1 << 7;
14789        public static final int DUMP_VERIFIERS = 1 << 8;
14790        public static final int DUMP_PREFERRED = 1 << 9;
14791        public static final int DUMP_PREFERRED_XML = 1 << 10;
14792        public static final int DUMP_KEYSETS = 1 << 11;
14793        public static final int DUMP_VERSION = 1 << 12;
14794        public static final int DUMP_INSTALLS = 1 << 13;
14795        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14796        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14797
14798        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14799
14800        private int mTypes;
14801
14802        private int mOptions;
14803
14804        private boolean mTitlePrinted;
14805
14806        private SharedUserSetting mSharedUser;
14807
14808        public boolean isDumping(int type) {
14809            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14810                return true;
14811            }
14812
14813            return (mTypes & type) != 0;
14814        }
14815
14816        public void setDump(int type) {
14817            mTypes |= type;
14818        }
14819
14820        public boolean isOptionEnabled(int option) {
14821            return (mOptions & option) != 0;
14822        }
14823
14824        public void setOptionEnabled(int option) {
14825            mOptions |= option;
14826        }
14827
14828        public boolean onTitlePrinted() {
14829            final boolean printed = mTitlePrinted;
14830            mTitlePrinted = true;
14831            return printed;
14832        }
14833
14834        public boolean getTitlePrinted() {
14835            return mTitlePrinted;
14836        }
14837
14838        public void setTitlePrinted(boolean enabled) {
14839            mTitlePrinted = enabled;
14840        }
14841
14842        public SharedUserSetting getSharedUser() {
14843            return mSharedUser;
14844        }
14845
14846        public void setSharedUser(SharedUserSetting user) {
14847            mSharedUser = user;
14848        }
14849    }
14850
14851    @Override
14852    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14853        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14854                != PackageManager.PERMISSION_GRANTED) {
14855            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14856                    + Binder.getCallingPid()
14857                    + ", uid=" + Binder.getCallingUid()
14858                    + " without permission "
14859                    + android.Manifest.permission.DUMP);
14860            return;
14861        }
14862
14863        DumpState dumpState = new DumpState();
14864        boolean fullPreferred = false;
14865        boolean checkin = false;
14866
14867        String packageName = null;
14868        ArraySet<String> permissionNames = null;
14869
14870        int opti = 0;
14871        while (opti < args.length) {
14872            String opt = args[opti];
14873            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14874                break;
14875            }
14876            opti++;
14877
14878            if ("-a".equals(opt)) {
14879                // Right now we only know how to print all.
14880            } else if ("-h".equals(opt)) {
14881                pw.println("Package manager dump options:");
14882                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14883                pw.println("    --checkin: dump for a checkin");
14884                pw.println("    -f: print details of intent filters");
14885                pw.println("    -h: print this help");
14886                pw.println("  cmd may be one of:");
14887                pw.println("    l[ibraries]: list known shared libraries");
14888                pw.println("    f[ibraries]: list device features");
14889                pw.println("    k[eysets]: print known keysets");
14890                pw.println("    r[esolvers]: dump intent resolvers");
14891                pw.println("    perm[issions]: dump permissions");
14892                pw.println("    permission [name ...]: dump declaration and use of given permission");
14893                pw.println("    pref[erred]: print preferred package settings");
14894                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14895                pw.println("    prov[iders]: dump content providers");
14896                pw.println("    p[ackages]: dump installed packages");
14897                pw.println("    s[hared-users]: dump shared user IDs");
14898                pw.println("    m[essages]: print collected runtime messages");
14899                pw.println("    v[erifiers]: print package verifier info");
14900                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14901                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14902                pw.println("    version: print database version info");
14903                pw.println("    write: write current settings now");
14904                pw.println("    installs: details about install sessions");
14905                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14906                pw.println("    <package.name>: info about given package");
14907                return;
14908            } else if ("--checkin".equals(opt)) {
14909                checkin = true;
14910            } else if ("-f".equals(opt)) {
14911                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14912            } else {
14913                pw.println("Unknown argument: " + opt + "; use -h for help");
14914            }
14915        }
14916
14917        // Is the caller requesting to dump a particular piece of data?
14918        if (opti < args.length) {
14919            String cmd = args[opti];
14920            opti++;
14921            // Is this a package name?
14922            if ("android".equals(cmd) || cmd.contains(".")) {
14923                packageName = cmd;
14924                // When dumping a single package, we always dump all of its
14925                // filter information since the amount of data will be reasonable.
14926                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14927            } else if ("check-permission".equals(cmd)) {
14928                if (opti >= args.length) {
14929                    pw.println("Error: check-permission missing permission argument");
14930                    return;
14931                }
14932                String perm = args[opti];
14933                opti++;
14934                if (opti >= args.length) {
14935                    pw.println("Error: check-permission missing package argument");
14936                    return;
14937                }
14938                String pkg = args[opti];
14939                opti++;
14940                int user = UserHandle.getUserId(Binder.getCallingUid());
14941                if (opti < args.length) {
14942                    try {
14943                        user = Integer.parseInt(args[opti]);
14944                    } catch (NumberFormatException e) {
14945                        pw.println("Error: check-permission user argument is not a number: "
14946                                + args[opti]);
14947                        return;
14948                    }
14949                }
14950                pw.println(checkPermission(perm, pkg, user));
14951                return;
14952            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14953                dumpState.setDump(DumpState.DUMP_LIBS);
14954            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14955                dumpState.setDump(DumpState.DUMP_FEATURES);
14956            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14957                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14958            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14959                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14960            } else if ("permission".equals(cmd)) {
14961                if (opti >= args.length) {
14962                    pw.println("Error: permission requires permission name");
14963                    return;
14964                }
14965                permissionNames = new ArraySet<>();
14966                while (opti < args.length) {
14967                    permissionNames.add(args[opti]);
14968                    opti++;
14969                }
14970                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14971                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14972            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14973                dumpState.setDump(DumpState.DUMP_PREFERRED);
14974            } else if ("preferred-xml".equals(cmd)) {
14975                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14976                if (opti < args.length && "--full".equals(args[opti])) {
14977                    fullPreferred = true;
14978                    opti++;
14979                }
14980            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14981                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14982            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14983                dumpState.setDump(DumpState.DUMP_PACKAGES);
14984            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14985                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14986            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14987                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14988            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14989                dumpState.setDump(DumpState.DUMP_MESSAGES);
14990            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14991                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14992            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14993                    || "intent-filter-verifiers".equals(cmd)) {
14994                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14995            } else if ("version".equals(cmd)) {
14996                dumpState.setDump(DumpState.DUMP_VERSION);
14997            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14998                dumpState.setDump(DumpState.DUMP_KEYSETS);
14999            } else if ("installs".equals(cmd)) {
15000                dumpState.setDump(DumpState.DUMP_INSTALLS);
15001            } else if ("write".equals(cmd)) {
15002                synchronized (mPackages) {
15003                    mSettings.writeLPr();
15004                    pw.println("Settings written.");
15005                    return;
15006                }
15007            }
15008        }
15009
15010        if (checkin) {
15011            pw.println("vers,1");
15012        }
15013
15014        // reader
15015        synchronized (mPackages) {
15016            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15017                if (!checkin) {
15018                    if (dumpState.onTitlePrinted())
15019                        pw.println();
15020                    pw.println("Database versions:");
15021                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15022                }
15023            }
15024
15025            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15026                if (!checkin) {
15027                    if (dumpState.onTitlePrinted())
15028                        pw.println();
15029                    pw.println("Verifiers:");
15030                    pw.print("  Required: ");
15031                    pw.print(mRequiredVerifierPackage);
15032                    pw.print(" (uid=");
15033                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15034                    pw.println(")");
15035                } else if (mRequiredVerifierPackage != null) {
15036                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15037                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15038                }
15039            }
15040
15041            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15042                    packageName == null) {
15043                if (mIntentFilterVerifierComponent != null) {
15044                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15045                    if (!checkin) {
15046                        if (dumpState.onTitlePrinted())
15047                            pw.println();
15048                        pw.println("Intent Filter Verifier:");
15049                        pw.print("  Using: ");
15050                        pw.print(verifierPackageName);
15051                        pw.print(" (uid=");
15052                        pw.print(getPackageUid(verifierPackageName, 0));
15053                        pw.println(")");
15054                    } else if (verifierPackageName != null) {
15055                        pw.print("ifv,"); pw.print(verifierPackageName);
15056                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15057                    }
15058                } else {
15059                    pw.println();
15060                    pw.println("No Intent Filter Verifier available!");
15061                }
15062            }
15063
15064            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15065                boolean printedHeader = false;
15066                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15067                while (it.hasNext()) {
15068                    String name = it.next();
15069                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15070                    if (!checkin) {
15071                        if (!printedHeader) {
15072                            if (dumpState.onTitlePrinted())
15073                                pw.println();
15074                            pw.println("Libraries:");
15075                            printedHeader = true;
15076                        }
15077                        pw.print("  ");
15078                    } else {
15079                        pw.print("lib,");
15080                    }
15081                    pw.print(name);
15082                    if (!checkin) {
15083                        pw.print(" -> ");
15084                    }
15085                    if (ent.path != null) {
15086                        if (!checkin) {
15087                            pw.print("(jar) ");
15088                            pw.print(ent.path);
15089                        } else {
15090                            pw.print(",jar,");
15091                            pw.print(ent.path);
15092                        }
15093                    } else {
15094                        if (!checkin) {
15095                            pw.print("(apk) ");
15096                            pw.print(ent.apk);
15097                        } else {
15098                            pw.print(",apk,");
15099                            pw.print(ent.apk);
15100                        }
15101                    }
15102                    pw.println();
15103                }
15104            }
15105
15106            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15107                if (dumpState.onTitlePrinted())
15108                    pw.println();
15109                if (!checkin) {
15110                    pw.println("Features:");
15111                }
15112                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15113                while (it.hasNext()) {
15114                    String name = it.next();
15115                    if (!checkin) {
15116                        pw.print("  ");
15117                    } else {
15118                        pw.print("feat,");
15119                    }
15120                    pw.println(name);
15121                }
15122            }
15123
15124            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15125                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15126                        : "Activity Resolver Table:", "  ", packageName,
15127                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15128                    dumpState.setTitlePrinted(true);
15129                }
15130                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15131                        : "Receiver Resolver Table:", "  ", packageName,
15132                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15133                    dumpState.setTitlePrinted(true);
15134                }
15135                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15136                        : "Service Resolver Table:", "  ", packageName,
15137                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15138                    dumpState.setTitlePrinted(true);
15139                }
15140                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15141                        : "Provider Resolver Table:", "  ", packageName,
15142                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15143                    dumpState.setTitlePrinted(true);
15144                }
15145            }
15146
15147            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15148                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15149                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15150                    int user = mSettings.mPreferredActivities.keyAt(i);
15151                    if (pir.dump(pw,
15152                            dumpState.getTitlePrinted()
15153                                ? "\nPreferred Activities User " + user + ":"
15154                                : "Preferred Activities User " + user + ":", "  ",
15155                            packageName, true, false)) {
15156                        dumpState.setTitlePrinted(true);
15157                    }
15158                }
15159            }
15160
15161            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15162                pw.flush();
15163                FileOutputStream fout = new FileOutputStream(fd);
15164                BufferedOutputStream str = new BufferedOutputStream(fout);
15165                XmlSerializer serializer = new FastXmlSerializer();
15166                try {
15167                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15168                    serializer.startDocument(null, true);
15169                    serializer.setFeature(
15170                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15171                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15172                    serializer.endDocument();
15173                    serializer.flush();
15174                } catch (IllegalArgumentException e) {
15175                    pw.println("Failed writing: " + e);
15176                } catch (IllegalStateException e) {
15177                    pw.println("Failed writing: " + e);
15178                } catch (IOException e) {
15179                    pw.println("Failed writing: " + e);
15180                }
15181            }
15182
15183            if (!checkin
15184                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15185                    && packageName == null) {
15186                pw.println();
15187                int count = mSettings.mPackages.size();
15188                if (count == 0) {
15189                    pw.println("No applications!");
15190                    pw.println();
15191                } else {
15192                    final String prefix = "  ";
15193                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15194                    if (allPackageSettings.size() == 0) {
15195                        pw.println("No domain preferred apps!");
15196                        pw.println();
15197                    } else {
15198                        pw.println("App verification status:");
15199                        pw.println();
15200                        count = 0;
15201                        for (PackageSetting ps : allPackageSettings) {
15202                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15203                            if (ivi == null || ivi.getPackageName() == null) continue;
15204                            pw.println(prefix + "Package: " + ivi.getPackageName());
15205                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15206                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15207                            pw.println();
15208                            count++;
15209                        }
15210                        if (count == 0) {
15211                            pw.println(prefix + "No app verification established.");
15212                            pw.println();
15213                        }
15214                        for (int userId : sUserManager.getUserIds()) {
15215                            pw.println("App linkages for user " + userId + ":");
15216                            pw.println();
15217                            count = 0;
15218                            for (PackageSetting ps : allPackageSettings) {
15219                                final long status = ps.getDomainVerificationStatusForUser(userId);
15220                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15221                                    continue;
15222                                }
15223                                pw.println(prefix + "Package: " + ps.name);
15224                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15225                                String statusStr = IntentFilterVerificationInfo.
15226                                        getStatusStringFromValue(status);
15227                                pw.println(prefix + "Status:  " + statusStr);
15228                                pw.println();
15229                                count++;
15230                            }
15231                            if (count == 0) {
15232                                pw.println(prefix + "No configured app linkages.");
15233                                pw.println();
15234                            }
15235                        }
15236                    }
15237                }
15238            }
15239
15240            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15241                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15242                if (packageName == null && permissionNames == null) {
15243                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15244                        if (iperm == 0) {
15245                            if (dumpState.onTitlePrinted())
15246                                pw.println();
15247                            pw.println("AppOp Permissions:");
15248                        }
15249                        pw.print("  AppOp Permission ");
15250                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15251                        pw.println(":");
15252                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15253                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15254                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15255                        }
15256                    }
15257                }
15258            }
15259
15260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15261                boolean printedSomething = false;
15262                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15263                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15264                        continue;
15265                    }
15266                    if (!printedSomething) {
15267                        if (dumpState.onTitlePrinted())
15268                            pw.println();
15269                        pw.println("Registered ContentProviders:");
15270                        printedSomething = true;
15271                    }
15272                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15273                    pw.print("    "); pw.println(p.toString());
15274                }
15275                printedSomething = false;
15276                for (Map.Entry<String, PackageParser.Provider> entry :
15277                        mProvidersByAuthority.entrySet()) {
15278                    PackageParser.Provider p = entry.getValue();
15279                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15280                        continue;
15281                    }
15282                    if (!printedSomething) {
15283                        if (dumpState.onTitlePrinted())
15284                            pw.println();
15285                        pw.println("ContentProvider Authorities:");
15286                        printedSomething = true;
15287                    }
15288                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15289                    pw.print("    "); pw.println(p.toString());
15290                    if (p.info != null && p.info.applicationInfo != null) {
15291                        final String appInfo = p.info.applicationInfo.toString();
15292                        pw.print("      applicationInfo="); pw.println(appInfo);
15293                    }
15294                }
15295            }
15296
15297            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15298                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15299            }
15300
15301            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15302                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15303            }
15304
15305            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15306                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15307            }
15308
15309            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15310                // XXX should handle packageName != null by dumping only install data that
15311                // the given package is involved with.
15312                if (dumpState.onTitlePrinted()) pw.println();
15313                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15314            }
15315
15316            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15317                if (dumpState.onTitlePrinted()) pw.println();
15318                mSettings.dumpReadMessagesLPr(pw, dumpState);
15319
15320                pw.println();
15321                pw.println("Package warning messages:");
15322                BufferedReader in = null;
15323                String line = null;
15324                try {
15325                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15326                    while ((line = in.readLine()) != null) {
15327                        if (line.contains("ignored: updated version")) continue;
15328                        pw.println(line);
15329                    }
15330                } catch (IOException ignored) {
15331                } finally {
15332                    IoUtils.closeQuietly(in);
15333                }
15334            }
15335
15336            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15337                BufferedReader in = null;
15338                String line = null;
15339                try {
15340                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15341                    while ((line = in.readLine()) != null) {
15342                        if (line.contains("ignored: updated version")) continue;
15343                        pw.print("msg,");
15344                        pw.println(line);
15345                    }
15346                } catch (IOException ignored) {
15347                } finally {
15348                    IoUtils.closeQuietly(in);
15349                }
15350            }
15351        }
15352    }
15353
15354    private String dumpDomainString(String packageName) {
15355        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15356        List<IntentFilter> filters = getAllIntentFilters(packageName);
15357
15358        ArraySet<String> result = new ArraySet<>();
15359        if (iviList.size() > 0) {
15360            for (IntentFilterVerificationInfo ivi : iviList) {
15361                for (String host : ivi.getDomains()) {
15362                    result.add(host);
15363                }
15364            }
15365        }
15366        if (filters != null && filters.size() > 0) {
15367            for (IntentFilter filter : filters) {
15368                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15369                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15370                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15371                    result.addAll(filter.getHostsList());
15372                }
15373            }
15374        }
15375
15376        StringBuilder sb = new StringBuilder(result.size() * 16);
15377        for (String domain : result) {
15378            if (sb.length() > 0) sb.append(" ");
15379            sb.append(domain);
15380        }
15381        return sb.toString();
15382    }
15383
15384    // ------- apps on sdcard specific code -------
15385    static final boolean DEBUG_SD_INSTALL = false;
15386
15387    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15388
15389    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15390
15391    private boolean mMediaMounted = false;
15392
15393    static String getEncryptKey() {
15394        try {
15395            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15396                    SD_ENCRYPTION_KEYSTORE_NAME);
15397            if (sdEncKey == null) {
15398                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15399                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15400                if (sdEncKey == null) {
15401                    Slog.e(TAG, "Failed to create encryption keys");
15402                    return null;
15403                }
15404            }
15405            return sdEncKey;
15406        } catch (NoSuchAlgorithmException nsae) {
15407            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15408            return null;
15409        } catch (IOException ioe) {
15410            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15411            return null;
15412        }
15413    }
15414
15415    /*
15416     * Update media status on PackageManager.
15417     */
15418    @Override
15419    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15420        int callingUid = Binder.getCallingUid();
15421        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15422            throw new SecurityException("Media status can only be updated by the system");
15423        }
15424        // reader; this apparently protects mMediaMounted, but should probably
15425        // be a different lock in that case.
15426        synchronized (mPackages) {
15427            Log.i(TAG, "Updating external media status from "
15428                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15429                    + (mediaStatus ? "mounted" : "unmounted"));
15430            if (DEBUG_SD_INSTALL)
15431                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15432                        + ", mMediaMounted=" + mMediaMounted);
15433            if (mediaStatus == mMediaMounted) {
15434                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15435                        : 0, -1);
15436                mHandler.sendMessage(msg);
15437                return;
15438            }
15439            mMediaMounted = mediaStatus;
15440        }
15441        // Queue up an async operation since the package installation may take a
15442        // little while.
15443        mHandler.post(new Runnable() {
15444            public void run() {
15445                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15446            }
15447        });
15448    }
15449
15450    /**
15451     * Called by MountService when the initial ASECs to scan are available.
15452     * Should block until all the ASEC containers are finished being scanned.
15453     */
15454    public void scanAvailableAsecs() {
15455        updateExternalMediaStatusInner(true, false, false);
15456        if (mShouldRestoreconData) {
15457            SELinuxMMAC.setRestoreconDone();
15458            mShouldRestoreconData = false;
15459        }
15460    }
15461
15462    /*
15463     * Collect information of applications on external media, map them against
15464     * existing containers and update information based on current mount status.
15465     * Please note that we always have to report status if reportStatus has been
15466     * set to true especially when unloading packages.
15467     */
15468    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15469            boolean externalStorage) {
15470        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15471        int[] uidArr = EmptyArray.INT;
15472
15473        final String[] list = PackageHelper.getSecureContainerList();
15474        if (ArrayUtils.isEmpty(list)) {
15475            Log.i(TAG, "No secure containers found");
15476        } else {
15477            // Process list of secure containers and categorize them
15478            // as active or stale based on their package internal state.
15479
15480            // reader
15481            synchronized (mPackages) {
15482                for (String cid : list) {
15483                    // Leave stages untouched for now; installer service owns them
15484                    if (PackageInstallerService.isStageName(cid)) continue;
15485
15486                    if (DEBUG_SD_INSTALL)
15487                        Log.i(TAG, "Processing container " + cid);
15488                    String pkgName = getAsecPackageName(cid);
15489                    if (pkgName == null) {
15490                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15491                        continue;
15492                    }
15493                    if (DEBUG_SD_INSTALL)
15494                        Log.i(TAG, "Looking for pkg : " + pkgName);
15495
15496                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15497                    if (ps == null) {
15498                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15499                        continue;
15500                    }
15501
15502                    /*
15503                     * Skip packages that are not external if we're unmounting
15504                     * external storage.
15505                     */
15506                    if (externalStorage && !isMounted && !isExternal(ps)) {
15507                        continue;
15508                    }
15509
15510                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15511                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15512                    // The package status is changed only if the code path
15513                    // matches between settings and the container id.
15514                    if (ps.codePathString != null
15515                            && ps.codePathString.startsWith(args.getCodePath())) {
15516                        if (DEBUG_SD_INSTALL) {
15517                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15518                                    + " at code path: " + ps.codePathString);
15519                        }
15520
15521                        // We do have a valid package installed on sdcard
15522                        processCids.put(args, ps.codePathString);
15523                        final int uid = ps.appId;
15524                        if (uid != -1) {
15525                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15526                        }
15527                    } else {
15528                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15529                                + ps.codePathString);
15530                    }
15531                }
15532            }
15533
15534            Arrays.sort(uidArr);
15535        }
15536
15537        // Process packages with valid entries.
15538        if (isMounted) {
15539            if (DEBUG_SD_INSTALL)
15540                Log.i(TAG, "Loading packages");
15541            loadMediaPackages(processCids, uidArr, externalStorage);
15542            startCleaningPackages();
15543            mInstallerService.onSecureContainersAvailable();
15544        } else {
15545            if (DEBUG_SD_INSTALL)
15546                Log.i(TAG, "Unloading packages");
15547            unloadMediaPackages(processCids, uidArr, reportStatus);
15548        }
15549    }
15550
15551    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15552            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15553        final int size = infos.size();
15554        final String[] packageNames = new String[size];
15555        final int[] packageUids = new int[size];
15556        for (int i = 0; i < size; i++) {
15557            final ApplicationInfo info = infos.get(i);
15558            packageNames[i] = info.packageName;
15559            packageUids[i] = info.uid;
15560        }
15561        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15562                finishedReceiver);
15563    }
15564
15565    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15566            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15567        sendResourcesChangedBroadcast(mediaStatus, replacing,
15568                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15569    }
15570
15571    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15572            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15573        int size = pkgList.length;
15574        if (size > 0) {
15575            // Send broadcasts here
15576            Bundle extras = new Bundle();
15577            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15578            if (uidArr != null) {
15579                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15580            }
15581            if (replacing) {
15582                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15583            }
15584            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15585                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15586            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15587        }
15588    }
15589
15590   /*
15591     * Look at potentially valid container ids from processCids If package
15592     * information doesn't match the one on record or package scanning fails,
15593     * the cid is added to list of removeCids. We currently don't delete stale
15594     * containers.
15595     */
15596    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15597            boolean externalStorage) {
15598        ArrayList<String> pkgList = new ArrayList<String>();
15599        Set<AsecInstallArgs> keys = processCids.keySet();
15600
15601        for (AsecInstallArgs args : keys) {
15602            String codePath = processCids.get(args);
15603            if (DEBUG_SD_INSTALL)
15604                Log.i(TAG, "Loading container : " + args.cid);
15605            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15606            try {
15607                // Make sure there are no container errors first.
15608                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15609                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15610                            + " when installing from sdcard");
15611                    continue;
15612                }
15613                // Check code path here.
15614                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15615                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15616                            + " does not match one in settings " + codePath);
15617                    continue;
15618                }
15619                // Parse package
15620                int parseFlags = mDefParseFlags;
15621                if (args.isExternalAsec()) {
15622                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15623                }
15624                if (args.isFwdLocked()) {
15625                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15626                }
15627
15628                synchronized (mInstallLock) {
15629                    PackageParser.Package pkg = null;
15630                    try {
15631                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15632                    } catch (PackageManagerException e) {
15633                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15634                    }
15635                    // Scan the package
15636                    if (pkg != null) {
15637                        /*
15638                         * TODO why is the lock being held? doPostInstall is
15639                         * called in other places without the lock. This needs
15640                         * to be straightened out.
15641                         */
15642                        // writer
15643                        synchronized (mPackages) {
15644                            retCode = PackageManager.INSTALL_SUCCEEDED;
15645                            pkgList.add(pkg.packageName);
15646                            // Post process args
15647                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15648                                    pkg.applicationInfo.uid);
15649                        }
15650                    } else {
15651                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15652                    }
15653                }
15654
15655            } finally {
15656                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15657                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15658                }
15659            }
15660        }
15661        // writer
15662        synchronized (mPackages) {
15663            // If the platform SDK has changed since the last time we booted,
15664            // we need to re-grant app permission to catch any new ones that
15665            // appear. This is really a hack, and means that apps can in some
15666            // cases get permissions that the user didn't initially explicitly
15667            // allow... it would be nice to have some better way to handle
15668            // this situation.
15669            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15670                    : mSettings.getInternalVersion();
15671            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15672                    : StorageManager.UUID_PRIVATE_INTERNAL;
15673
15674            int updateFlags = UPDATE_PERMISSIONS_ALL;
15675            if (ver.sdkVersion != mSdkVersion) {
15676                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15677                        + mSdkVersion + "; regranting permissions for external");
15678                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15679            }
15680            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15681
15682            // Yay, everything is now upgraded
15683            ver.forceCurrent();
15684
15685            // can downgrade to reader
15686            // Persist settings
15687            mSettings.writeLPr();
15688        }
15689        // Send a broadcast to let everyone know we are done processing
15690        if (pkgList.size() > 0) {
15691            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15692        }
15693    }
15694
15695   /*
15696     * Utility method to unload a list of specified containers
15697     */
15698    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15699        // Just unmount all valid containers.
15700        for (AsecInstallArgs arg : cidArgs) {
15701            synchronized (mInstallLock) {
15702                arg.doPostDeleteLI(false);
15703           }
15704       }
15705   }
15706
15707    /*
15708     * Unload packages mounted on external media. This involves deleting package
15709     * data from internal structures, sending broadcasts about diabled packages,
15710     * gc'ing to free up references, unmounting all secure containers
15711     * corresponding to packages on external media, and posting a
15712     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15713     * that we always have to post this message if status has been requested no
15714     * matter what.
15715     */
15716    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15717            final boolean reportStatus) {
15718        if (DEBUG_SD_INSTALL)
15719            Log.i(TAG, "unloading media packages");
15720        ArrayList<String> pkgList = new ArrayList<String>();
15721        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15722        final Set<AsecInstallArgs> keys = processCids.keySet();
15723        for (AsecInstallArgs args : keys) {
15724            String pkgName = args.getPackageName();
15725            if (DEBUG_SD_INSTALL)
15726                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15727            // Delete package internally
15728            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15729            synchronized (mInstallLock) {
15730                boolean res = deletePackageLI(pkgName, null, false, null, null,
15731                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15732                if (res) {
15733                    pkgList.add(pkgName);
15734                } else {
15735                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15736                    failedList.add(args);
15737                }
15738            }
15739        }
15740
15741        // reader
15742        synchronized (mPackages) {
15743            // We didn't update the settings after removing each package;
15744            // write them now for all packages.
15745            mSettings.writeLPr();
15746        }
15747
15748        // We have to absolutely send UPDATED_MEDIA_STATUS only
15749        // after confirming that all the receivers processed the ordered
15750        // broadcast when packages get disabled, force a gc to clean things up.
15751        // and unload all the containers.
15752        if (pkgList.size() > 0) {
15753            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15754                    new IIntentReceiver.Stub() {
15755                public void performReceive(Intent intent, int resultCode, String data,
15756                        Bundle extras, boolean ordered, boolean sticky,
15757                        int sendingUser) throws RemoteException {
15758                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15759                            reportStatus ? 1 : 0, 1, keys);
15760                    mHandler.sendMessage(msg);
15761                }
15762            });
15763        } else {
15764            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15765                    keys);
15766            mHandler.sendMessage(msg);
15767        }
15768    }
15769
15770    private void loadPrivatePackages(final VolumeInfo vol) {
15771        mHandler.post(new Runnable() {
15772            @Override
15773            public void run() {
15774                loadPrivatePackagesInner(vol);
15775            }
15776        });
15777    }
15778
15779    private void loadPrivatePackagesInner(VolumeInfo vol) {
15780        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15781        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15782
15783        final VersionInfo ver;
15784        final List<PackageSetting> packages;
15785        synchronized (mPackages) {
15786            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15787            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15788        }
15789
15790        for (PackageSetting ps : packages) {
15791            synchronized (mInstallLock) {
15792                final PackageParser.Package pkg;
15793                try {
15794                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15795                    loaded.add(pkg.applicationInfo);
15796                } catch (PackageManagerException e) {
15797                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15798                }
15799
15800                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15801                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15802                }
15803            }
15804        }
15805
15806        synchronized (mPackages) {
15807            int updateFlags = UPDATE_PERMISSIONS_ALL;
15808            if (ver.sdkVersion != mSdkVersion) {
15809                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15810                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15811                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15812            }
15813            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15814
15815            // Yay, everything is now upgraded
15816            ver.forceCurrent();
15817
15818            mSettings.writeLPr();
15819        }
15820
15821        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15822        sendResourcesChangedBroadcast(true, false, loaded, null);
15823    }
15824
15825    private void unloadPrivatePackages(final VolumeInfo vol) {
15826        mHandler.post(new Runnable() {
15827            @Override
15828            public void run() {
15829                unloadPrivatePackagesInner(vol);
15830            }
15831        });
15832    }
15833
15834    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15835        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15836        synchronized (mInstallLock) {
15837        synchronized (mPackages) {
15838            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15839            for (PackageSetting ps : packages) {
15840                if (ps.pkg == null) continue;
15841
15842                final ApplicationInfo info = ps.pkg.applicationInfo;
15843                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15844                if (deletePackageLI(ps.name, null, false, null, null,
15845                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15846                    unloaded.add(info);
15847                } else {
15848                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15849                }
15850            }
15851
15852            mSettings.writeLPr();
15853        }
15854        }
15855
15856        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15857        sendResourcesChangedBroadcast(false, false, unloaded, null);
15858    }
15859
15860    /**
15861     * Examine all users present on given mounted volume, and destroy data
15862     * belonging to users that are no longer valid, or whose user ID has been
15863     * recycled.
15864     */
15865    private void reconcileUsers(String volumeUuid) {
15866        final File[] files = FileUtils
15867                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15868        for (File file : files) {
15869            if (!file.isDirectory()) continue;
15870
15871            final int userId;
15872            final UserInfo info;
15873            try {
15874                userId = Integer.parseInt(file.getName());
15875                info = sUserManager.getUserInfo(userId);
15876            } catch (NumberFormatException e) {
15877                Slog.w(TAG, "Invalid user directory " + file);
15878                continue;
15879            }
15880
15881            boolean destroyUser = false;
15882            if (info == null) {
15883                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15884                        + " because no matching user was found");
15885                destroyUser = true;
15886            } else {
15887                try {
15888                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15889                } catch (IOException e) {
15890                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15891                            + " because we failed to enforce serial number: " + e);
15892                    destroyUser = true;
15893                }
15894            }
15895
15896            if (destroyUser) {
15897                synchronized (mInstallLock) {
15898                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15899                }
15900            }
15901        }
15902
15903        final UserManager um = mContext.getSystemService(UserManager.class);
15904        for (UserInfo user : um.getUsers()) {
15905            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15906            if (userDir.exists()) continue;
15907
15908            try {
15909                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15910                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15911            } catch (IOException e) {
15912                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15913            }
15914        }
15915    }
15916
15917    /**
15918     * Examine all apps present on given mounted volume, and destroy apps that
15919     * aren't expected, either due to uninstallation or reinstallation on
15920     * another volume.
15921     */
15922    private void reconcileApps(String volumeUuid) {
15923        final File[] files = FileUtils
15924                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15925        for (File file : files) {
15926            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15927                    && !PackageInstallerService.isStageName(file.getName());
15928            if (!isPackage) {
15929                // Ignore entries which are not packages
15930                continue;
15931            }
15932
15933            boolean destroyApp = false;
15934            String packageName = null;
15935            try {
15936                final PackageLite pkg = PackageParser.parsePackageLite(file,
15937                        PackageParser.PARSE_MUST_BE_APK);
15938                packageName = pkg.packageName;
15939
15940                synchronized (mPackages) {
15941                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15942                    if (ps == null) {
15943                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15944                                + volumeUuid + " because we found no install record");
15945                        destroyApp = true;
15946                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15947                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15948                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15949                        destroyApp = true;
15950                    }
15951                }
15952
15953            } catch (PackageParserException e) {
15954                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15955                destroyApp = true;
15956            }
15957
15958            if (destroyApp) {
15959                synchronized (mInstallLock) {
15960                    if (packageName != null) {
15961                        removeDataDirsLI(volumeUuid, packageName);
15962                    }
15963                    if (file.isDirectory()) {
15964                        mInstaller.rmPackageDir(file.getAbsolutePath());
15965                    } else {
15966                        file.delete();
15967                    }
15968                }
15969            }
15970        }
15971    }
15972
15973    private void unfreezePackage(String packageName) {
15974        synchronized (mPackages) {
15975            final PackageSetting ps = mSettings.mPackages.get(packageName);
15976            if (ps != null) {
15977                ps.frozen = false;
15978            }
15979        }
15980    }
15981
15982    @Override
15983    public int movePackage(final String packageName, final String volumeUuid) {
15984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15985
15986        final int moveId = mNextMoveId.getAndIncrement();
15987        try {
15988            movePackageInternal(packageName, volumeUuid, moveId);
15989        } catch (PackageManagerException e) {
15990            Slog.w(TAG, "Failed to move " + packageName, e);
15991            mMoveCallbacks.notifyStatusChanged(moveId,
15992                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15993        }
15994        return moveId;
15995    }
15996
15997    private void movePackageInternal(final String packageName, final String volumeUuid,
15998            final int moveId) throws PackageManagerException {
15999        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16000        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16001        final PackageManager pm = mContext.getPackageManager();
16002
16003        final boolean currentAsec;
16004        final String currentVolumeUuid;
16005        final File codeFile;
16006        final String installerPackageName;
16007        final String packageAbiOverride;
16008        final int appId;
16009        final String seinfo;
16010        final String label;
16011
16012        // reader
16013        synchronized (mPackages) {
16014            final PackageParser.Package pkg = mPackages.get(packageName);
16015            final PackageSetting ps = mSettings.mPackages.get(packageName);
16016            if (pkg == null || ps == null) {
16017                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16018            }
16019
16020            if (pkg.applicationInfo.isSystemApp()) {
16021                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16022                        "Cannot move system application");
16023            }
16024
16025            if (pkg.applicationInfo.isExternalAsec()) {
16026                currentAsec = true;
16027                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16028            } else if (pkg.applicationInfo.isForwardLocked()) {
16029                currentAsec = true;
16030                currentVolumeUuid = "forward_locked";
16031            } else {
16032                currentAsec = false;
16033                currentVolumeUuid = ps.volumeUuid;
16034
16035                final File probe = new File(pkg.codePath);
16036                final File probeOat = new File(probe, "oat");
16037                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16038                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16039                            "Move only supported for modern cluster style installs");
16040                }
16041            }
16042
16043            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16044                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16045                        "Package already moved to " + volumeUuid);
16046            }
16047
16048            if (ps.frozen) {
16049                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16050                        "Failed to move already frozen package");
16051            }
16052            ps.frozen = true;
16053
16054            codeFile = new File(pkg.codePath);
16055            installerPackageName = ps.installerPackageName;
16056            packageAbiOverride = ps.cpuAbiOverrideString;
16057            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16058            seinfo = pkg.applicationInfo.seinfo;
16059            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16060        }
16061
16062        // Now that we're guarded by frozen state, kill app during move
16063        final long token = Binder.clearCallingIdentity();
16064        try {
16065            killApplication(packageName, appId, "move pkg");
16066        } finally {
16067            Binder.restoreCallingIdentity(token);
16068        }
16069
16070        final Bundle extras = new Bundle();
16071        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16072        extras.putString(Intent.EXTRA_TITLE, label);
16073        mMoveCallbacks.notifyCreated(moveId, extras);
16074
16075        int installFlags;
16076        final boolean moveCompleteApp;
16077        final File measurePath;
16078
16079        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16080            installFlags = INSTALL_INTERNAL;
16081            moveCompleteApp = !currentAsec;
16082            measurePath = Environment.getDataAppDirectory(volumeUuid);
16083        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16084            installFlags = INSTALL_EXTERNAL;
16085            moveCompleteApp = false;
16086            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16087        } else {
16088            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16089            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16090                    || !volume.isMountedWritable()) {
16091                unfreezePackage(packageName);
16092                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16093                        "Move location not mounted private volume");
16094            }
16095
16096            Preconditions.checkState(!currentAsec);
16097
16098            installFlags = INSTALL_INTERNAL;
16099            moveCompleteApp = true;
16100            measurePath = Environment.getDataAppDirectory(volumeUuid);
16101        }
16102
16103        final PackageStats stats = new PackageStats(null, -1);
16104        synchronized (mInstaller) {
16105            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16106                unfreezePackage(packageName);
16107                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16108                        "Failed to measure package size");
16109            }
16110        }
16111
16112        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16113                + stats.dataSize);
16114
16115        final long startFreeBytes = measurePath.getFreeSpace();
16116        final long sizeBytes;
16117        if (moveCompleteApp) {
16118            sizeBytes = stats.codeSize + stats.dataSize;
16119        } else {
16120            sizeBytes = stats.codeSize;
16121        }
16122
16123        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16124            unfreezePackage(packageName);
16125            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16126                    "Not enough free space to move");
16127        }
16128
16129        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16130
16131        final CountDownLatch installedLatch = new CountDownLatch(1);
16132        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16133            @Override
16134            public void onUserActionRequired(Intent intent) throws RemoteException {
16135                throw new IllegalStateException();
16136            }
16137
16138            @Override
16139            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16140                    Bundle extras) throws RemoteException {
16141                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16142                        + PackageManager.installStatusToString(returnCode, msg));
16143
16144                installedLatch.countDown();
16145
16146                // Regardless of success or failure of the move operation,
16147                // always unfreeze the package
16148                unfreezePackage(packageName);
16149
16150                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16151                switch (status) {
16152                    case PackageInstaller.STATUS_SUCCESS:
16153                        mMoveCallbacks.notifyStatusChanged(moveId,
16154                                PackageManager.MOVE_SUCCEEDED);
16155                        break;
16156                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16157                        mMoveCallbacks.notifyStatusChanged(moveId,
16158                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16159                        break;
16160                    default:
16161                        mMoveCallbacks.notifyStatusChanged(moveId,
16162                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16163                        break;
16164                }
16165            }
16166        };
16167
16168        final MoveInfo move;
16169        if (moveCompleteApp) {
16170            // Kick off a thread to report progress estimates
16171            new Thread() {
16172                @Override
16173                public void run() {
16174                    while (true) {
16175                        try {
16176                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16177                                break;
16178                            }
16179                        } catch (InterruptedException ignored) {
16180                        }
16181
16182                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16183                        final int progress = 10 + (int) MathUtils.constrain(
16184                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16185                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16186                    }
16187                }
16188            }.start();
16189
16190            final String dataAppName = codeFile.getName();
16191            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16192                    dataAppName, appId, seinfo);
16193        } else {
16194            move = null;
16195        }
16196
16197        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16198
16199        final Message msg = mHandler.obtainMessage(INIT_COPY);
16200        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16201        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16202                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16203        mHandler.sendMessage(msg);
16204    }
16205
16206    @Override
16207    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16208        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16209
16210        final int realMoveId = mNextMoveId.getAndIncrement();
16211        final Bundle extras = new Bundle();
16212        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16213        mMoveCallbacks.notifyCreated(realMoveId, extras);
16214
16215        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16216            @Override
16217            public void onCreated(int moveId, Bundle extras) {
16218                // Ignored
16219            }
16220
16221            @Override
16222            public void onStatusChanged(int moveId, int status, long estMillis) {
16223                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16224            }
16225        };
16226
16227        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16228        storage.setPrimaryStorageUuid(volumeUuid, callback);
16229        return realMoveId;
16230    }
16231
16232    @Override
16233    public int getMoveStatus(int moveId) {
16234        mContext.enforceCallingOrSelfPermission(
16235                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16236        return mMoveCallbacks.mLastStatus.get(moveId);
16237    }
16238
16239    @Override
16240    public void registerMoveCallback(IPackageMoveObserver callback) {
16241        mContext.enforceCallingOrSelfPermission(
16242                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16243        mMoveCallbacks.register(callback);
16244    }
16245
16246    @Override
16247    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16248        mContext.enforceCallingOrSelfPermission(
16249                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16250        mMoveCallbacks.unregister(callback);
16251    }
16252
16253    @Override
16254    public boolean setInstallLocation(int loc) {
16255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16256                null);
16257        if (getInstallLocation() == loc) {
16258            return true;
16259        }
16260        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16261                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16262            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16263                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16264            return true;
16265        }
16266        return false;
16267   }
16268
16269    @Override
16270    public int getInstallLocation() {
16271        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16272                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16273                PackageHelper.APP_INSTALL_AUTO);
16274    }
16275
16276    /** Called by UserManagerService */
16277    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16278        mDirtyUsers.remove(userHandle);
16279        mSettings.removeUserLPw(userHandle);
16280        mPendingBroadcasts.remove(userHandle);
16281        if (mInstaller != null) {
16282            // Technically, we shouldn't be doing this with the package lock
16283            // held.  However, this is very rare, and there is already so much
16284            // other disk I/O going on, that we'll let it slide for now.
16285            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16286            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16287                final String volumeUuid = vol.getFsUuid();
16288                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16289                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16290            }
16291        }
16292        mUserNeedsBadging.delete(userHandle);
16293        removeUnusedPackagesLILPw(userManager, userHandle);
16294    }
16295
16296    /**
16297     * We're removing userHandle and would like to remove any downloaded packages
16298     * that are no longer in use by any other user.
16299     * @param userHandle the user being removed
16300     */
16301    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16302        final boolean DEBUG_CLEAN_APKS = false;
16303        int [] users = userManager.getUserIdsLPr();
16304        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16305        while (psit.hasNext()) {
16306            PackageSetting ps = psit.next();
16307            if (ps.pkg == null) {
16308                continue;
16309            }
16310            final String packageName = ps.pkg.packageName;
16311            // Skip over if system app
16312            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16313                continue;
16314            }
16315            if (DEBUG_CLEAN_APKS) {
16316                Slog.i(TAG, "Checking package " + packageName);
16317            }
16318            boolean keep = false;
16319            for (int i = 0; i < users.length; i++) {
16320                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16321                    keep = true;
16322                    if (DEBUG_CLEAN_APKS) {
16323                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16324                                + users[i]);
16325                    }
16326                    break;
16327                }
16328            }
16329            if (!keep) {
16330                if (DEBUG_CLEAN_APKS) {
16331                    Slog.i(TAG, "  Removing package " + packageName);
16332                }
16333                mHandler.post(new Runnable() {
16334                    public void run() {
16335                        deletePackageX(packageName, userHandle, 0);
16336                    } //end run
16337                });
16338            }
16339        }
16340    }
16341
16342    /** Called by UserManagerService */
16343    void createNewUserLILPw(int userHandle) {
16344        if (mInstaller != null) {
16345            mInstaller.createUserConfig(userHandle);
16346            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16347            applyFactoryDefaultBrowserLPw(userHandle);
16348            primeDomainVerificationsLPw(userHandle);
16349        }
16350    }
16351
16352    void newUserCreated(final int userHandle) {
16353        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16354    }
16355
16356    @Override
16357    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16358        mContext.enforceCallingOrSelfPermission(
16359                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16360                "Only package verification agents can read the verifier device identity");
16361
16362        synchronized (mPackages) {
16363            return mSettings.getVerifierDeviceIdentityLPw();
16364        }
16365    }
16366
16367    @Override
16368    public void setPermissionEnforced(String permission, boolean enforced) {
16369        // TODO: Now that we no longer change GID for storage, this should to away.
16370        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16371                "setPermissionEnforced");
16372        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16373            synchronized (mPackages) {
16374                if (mSettings.mReadExternalStorageEnforced == null
16375                        || mSettings.mReadExternalStorageEnforced != enforced) {
16376                    mSettings.mReadExternalStorageEnforced = enforced;
16377                    mSettings.writeLPr();
16378                }
16379            }
16380            // kill any non-foreground processes so we restart them and
16381            // grant/revoke the GID.
16382            final IActivityManager am = ActivityManagerNative.getDefault();
16383            if (am != null) {
16384                final long token = Binder.clearCallingIdentity();
16385                try {
16386                    am.killProcessesBelowForeground("setPermissionEnforcement");
16387                } catch (RemoteException e) {
16388                } finally {
16389                    Binder.restoreCallingIdentity(token);
16390                }
16391            }
16392        } else {
16393            throw new IllegalArgumentException("No selective enforcement for " + permission);
16394        }
16395    }
16396
16397    @Override
16398    @Deprecated
16399    public boolean isPermissionEnforced(String permission) {
16400        return true;
16401    }
16402
16403    @Override
16404    public boolean isStorageLow() {
16405        final long token = Binder.clearCallingIdentity();
16406        try {
16407            final DeviceStorageMonitorInternal
16408                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16409            if (dsm != null) {
16410                return dsm.isMemoryLow();
16411            } else {
16412                return false;
16413            }
16414        } finally {
16415            Binder.restoreCallingIdentity(token);
16416        }
16417    }
16418
16419    @Override
16420    public IPackageInstaller getPackageInstaller() {
16421        return mInstallerService;
16422    }
16423
16424    private boolean userNeedsBadging(int userId) {
16425        int index = mUserNeedsBadging.indexOfKey(userId);
16426        if (index < 0) {
16427            final UserInfo userInfo;
16428            final long token = Binder.clearCallingIdentity();
16429            try {
16430                userInfo = sUserManager.getUserInfo(userId);
16431            } finally {
16432                Binder.restoreCallingIdentity(token);
16433            }
16434            final boolean b;
16435            if (userInfo != null && userInfo.isManagedProfile()) {
16436                b = true;
16437            } else {
16438                b = false;
16439            }
16440            mUserNeedsBadging.put(userId, b);
16441            return b;
16442        }
16443        return mUserNeedsBadging.valueAt(index);
16444    }
16445
16446    @Override
16447    public KeySet getKeySetByAlias(String packageName, String alias) {
16448        if (packageName == null || alias == null) {
16449            return null;
16450        }
16451        synchronized(mPackages) {
16452            final PackageParser.Package pkg = mPackages.get(packageName);
16453            if (pkg == null) {
16454                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16455                throw new IllegalArgumentException("Unknown package: " + packageName);
16456            }
16457            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16458            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16459        }
16460    }
16461
16462    @Override
16463    public KeySet getSigningKeySet(String packageName) {
16464        if (packageName == null) {
16465            return null;
16466        }
16467        synchronized(mPackages) {
16468            final PackageParser.Package pkg = mPackages.get(packageName);
16469            if (pkg == null) {
16470                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16471                throw new IllegalArgumentException("Unknown package: " + packageName);
16472            }
16473            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16474                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16475                throw new SecurityException("May not access signing KeySet of other apps.");
16476            }
16477            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16478            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16479        }
16480    }
16481
16482    @Override
16483    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16484        if (packageName == null || ks == null) {
16485            return false;
16486        }
16487        synchronized(mPackages) {
16488            final PackageParser.Package pkg = mPackages.get(packageName);
16489            if (pkg == null) {
16490                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16491                throw new IllegalArgumentException("Unknown package: " + packageName);
16492            }
16493            IBinder ksh = ks.getToken();
16494            if (ksh instanceof KeySetHandle) {
16495                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16496                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16497            }
16498            return false;
16499        }
16500    }
16501
16502    @Override
16503    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16504        if (packageName == null || ks == null) {
16505            return false;
16506        }
16507        synchronized(mPackages) {
16508            final PackageParser.Package pkg = mPackages.get(packageName);
16509            if (pkg == null) {
16510                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16511                throw new IllegalArgumentException("Unknown package: " + packageName);
16512            }
16513            IBinder ksh = ks.getToken();
16514            if (ksh instanceof KeySetHandle) {
16515                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16516                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16517            }
16518            return false;
16519        }
16520    }
16521
16522    public void getUsageStatsIfNoPackageUsageInfo() {
16523        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16524            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16525            if (usm == null) {
16526                throw new IllegalStateException("UsageStatsManager must be initialized");
16527            }
16528            long now = System.currentTimeMillis();
16529            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16530            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16531                String packageName = entry.getKey();
16532                PackageParser.Package pkg = mPackages.get(packageName);
16533                if (pkg == null) {
16534                    continue;
16535                }
16536                UsageStats usage = entry.getValue();
16537                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16538                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16539            }
16540        }
16541    }
16542
16543    /**
16544     * Check and throw if the given before/after packages would be considered a
16545     * downgrade.
16546     */
16547    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16548            throws PackageManagerException {
16549        if (after.versionCode < before.mVersionCode) {
16550            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16551                    "Update version code " + after.versionCode + " is older than current "
16552                    + before.mVersionCode);
16553        } else if (after.versionCode == before.mVersionCode) {
16554            if (after.baseRevisionCode < before.baseRevisionCode) {
16555                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16556                        "Update base revision code " + after.baseRevisionCode
16557                        + " is older than current " + before.baseRevisionCode);
16558            }
16559
16560            if (!ArrayUtils.isEmpty(after.splitNames)) {
16561                for (int i = 0; i < after.splitNames.length; i++) {
16562                    final String splitName = after.splitNames[i];
16563                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16564                    if (j != -1) {
16565                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16566                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16567                                    "Update split " + splitName + " revision code "
16568                                    + after.splitRevisionCodes[i] + " is older than current "
16569                                    + before.splitRevisionCodes[j]);
16570                        }
16571                    }
16572                }
16573            }
16574        }
16575    }
16576
16577    private static class MoveCallbacks extends Handler {
16578        private static final int MSG_CREATED = 1;
16579        private static final int MSG_STATUS_CHANGED = 2;
16580
16581        private final RemoteCallbackList<IPackageMoveObserver>
16582                mCallbacks = new RemoteCallbackList<>();
16583
16584        private final SparseIntArray mLastStatus = new SparseIntArray();
16585
16586        public MoveCallbacks(Looper looper) {
16587            super(looper);
16588        }
16589
16590        public void register(IPackageMoveObserver callback) {
16591            mCallbacks.register(callback);
16592        }
16593
16594        public void unregister(IPackageMoveObserver callback) {
16595            mCallbacks.unregister(callback);
16596        }
16597
16598        @Override
16599        public void handleMessage(Message msg) {
16600            final SomeArgs args = (SomeArgs) msg.obj;
16601            final int n = mCallbacks.beginBroadcast();
16602            for (int i = 0; i < n; i++) {
16603                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16604                try {
16605                    invokeCallback(callback, msg.what, args);
16606                } catch (RemoteException ignored) {
16607                }
16608            }
16609            mCallbacks.finishBroadcast();
16610            args.recycle();
16611        }
16612
16613        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16614                throws RemoteException {
16615            switch (what) {
16616                case MSG_CREATED: {
16617                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16618                    break;
16619                }
16620                case MSG_STATUS_CHANGED: {
16621                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16622                    break;
16623                }
16624            }
16625        }
16626
16627        private void notifyCreated(int moveId, Bundle extras) {
16628            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16629
16630            final SomeArgs args = SomeArgs.obtain();
16631            args.argi1 = moveId;
16632            args.arg2 = extras;
16633            obtainMessage(MSG_CREATED, args).sendToTarget();
16634        }
16635
16636        private void notifyStatusChanged(int moveId, int status) {
16637            notifyStatusChanged(moveId, status, -1);
16638        }
16639
16640        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16641            Slog.v(TAG, "Move " + moveId + " status " + status);
16642
16643            final SomeArgs args = SomeArgs.obtain();
16644            args.argi1 = moveId;
16645            args.argi2 = status;
16646            args.arg3 = estMillis;
16647            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16648
16649            synchronized (mLastStatus) {
16650                mLastStatus.put(moveId, status);
16651            }
16652        }
16653    }
16654
16655    private final class OnPermissionChangeListeners extends Handler {
16656        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16657
16658        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16659                new RemoteCallbackList<>();
16660
16661        public OnPermissionChangeListeners(Looper looper) {
16662            super(looper);
16663        }
16664
16665        @Override
16666        public void handleMessage(Message msg) {
16667            switch (msg.what) {
16668                case MSG_ON_PERMISSIONS_CHANGED: {
16669                    final int uid = msg.arg1;
16670                    handleOnPermissionsChanged(uid);
16671                } break;
16672            }
16673        }
16674
16675        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16676            mPermissionListeners.register(listener);
16677
16678        }
16679
16680        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16681            mPermissionListeners.unregister(listener);
16682        }
16683
16684        public void onPermissionsChanged(int uid) {
16685            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16686                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16687            }
16688        }
16689
16690        private void handleOnPermissionsChanged(int uid) {
16691            final int count = mPermissionListeners.beginBroadcast();
16692            try {
16693                for (int i = 0; i < count; i++) {
16694                    IOnPermissionsChangeListener callback = mPermissionListeners
16695                            .getBroadcastItem(i);
16696                    try {
16697                        callback.onPermissionsChanged(uid);
16698                    } catch (RemoteException e) {
16699                        Log.e(TAG, "Permission listener is dead", e);
16700                    }
16701                }
16702            } finally {
16703                mPermissionListeners.finishBroadcast();
16704            }
16705        }
16706    }
16707
16708    private class PackageManagerInternalImpl extends PackageManagerInternal {
16709        @Override
16710        public void setLocationPackagesProvider(PackagesProvider provider) {
16711            synchronized (mPackages) {
16712                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16713            }
16714        }
16715
16716        @Override
16717        public void setImePackagesProvider(PackagesProvider provider) {
16718            synchronized (mPackages) {
16719                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16720            }
16721        }
16722
16723        @Override
16724        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16725            synchronized (mPackages) {
16726                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16727            }
16728        }
16729
16730        @Override
16731        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16732            synchronized (mPackages) {
16733                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16734            }
16735        }
16736
16737        @Override
16738        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16739            synchronized (mPackages) {
16740                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16741            }
16742        }
16743
16744        @Override
16745        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16746            synchronized (mPackages) {
16747                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16748            }
16749        }
16750
16751        @Override
16752        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16753            synchronized (mPackages) {
16754                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16755            }
16756        }
16757
16758        @Override
16759        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16760            synchronized (mPackages) {
16761                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16762                        packageName, userId);
16763            }
16764        }
16765
16766        @Override
16767        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16768            synchronized (mPackages) {
16769                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16770                        packageName, userId);
16771            }
16772        }
16773        @Override
16774        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16775            synchronized (mPackages) {
16776                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16777                        packageName, userId);
16778            }
16779        }
16780    }
16781
16782    @Override
16783    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16784        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16785        synchronized (mPackages) {
16786            final long identity = Binder.clearCallingIdentity();
16787            try {
16788                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16789                        packageNames, userId);
16790            } finally {
16791                Binder.restoreCallingIdentity(identity);
16792            }
16793        }
16794    }
16795
16796    private static void enforceSystemOrPhoneCaller(String tag) {
16797        int callingUid = Binder.getCallingUid();
16798        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16799            throw new SecurityException(
16800                    "Cannot call " + tag + " from UID " + callingUid);
16801        }
16802    }
16803}
16804