PackageManagerService.java revision 01af6a42a6a008d4b208a92510537791b261168c
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, updateFlags);
2287            ver.sdkVersion = mSdkVersion;
2288
2289            // If this is the first boot or an update from pre-M, and it is a normal
2290            // boot, then we need to initialize the default preferred apps across
2291            // all defined users.
2292            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2293                for (UserInfo user : sUserManager.getUsers(true)) {
2294                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2295                    applyFactoryDefaultBrowserLPw(user.id);
2296                    primeDomainVerificationsLPw(user.id);
2297                }
2298            }
2299
2300            // If this is first boot after an OTA, and a normal boot, then
2301            // we need to clear code cache directories.
2302            if (mIsUpgrade && !onlyCore) {
2303                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2304                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2305                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2306                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2307                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2308                    }
2309                }
2310                ver.fingerprint = Build.FINGERPRINT;
2311            }
2312
2313            checkDefaultBrowser();
2314
2315            // clear only after permissions and other defaults have been updated
2316            mExistingSystemPackages.clear();
2317            mPromoteSystemApps = false;
2318
2319            // All the changes are done during package scanning.
2320            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2321
2322            // can downgrade to reader
2323            mSettings.writeLPr();
2324
2325            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2326                    SystemClock.uptimeMillis());
2327
2328            mRequiredVerifierPackage = getRequiredVerifierLPr();
2329            mRequiredInstallerPackage = getRequiredInstallerLPr();
2330
2331            mInstallerService = new PackageInstallerService(context, this);
2332
2333            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2334            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2335                    mIntentFilterVerifierComponent);
2336
2337        } // synchronized (mPackages)
2338        } // synchronized (mInstallLock)
2339
2340        // Now after opening every single application zip, make sure they
2341        // are all flushed.  Not really needed, but keeps things nice and
2342        // tidy.
2343        Runtime.getRuntime().gc();
2344
2345        // Expose private service for system components to use.
2346        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2347    }
2348
2349    @Override
2350    public boolean isFirstBoot() {
2351        return !mRestoredSettings;
2352    }
2353
2354    @Override
2355    public boolean isOnlyCoreApps() {
2356        return mOnlyCore;
2357    }
2358
2359    @Override
2360    public boolean isUpgrade() {
2361        return mIsUpgrade;
2362    }
2363
2364    private String getRequiredVerifierLPr() {
2365        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2366        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2367                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2368
2369        String requiredVerifier = null;
2370
2371        final int N = receivers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = receivers.get(i);
2374
2375            if (info.activityInfo == null) {
2376                continue;
2377            }
2378
2379            final String packageName = info.activityInfo.packageName;
2380
2381            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2382                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2383                continue;
2384            }
2385
2386            if (requiredVerifier != null) {
2387                throw new RuntimeException("There can be only one required verifier");
2388            }
2389
2390            requiredVerifier = packageName;
2391        }
2392
2393        return requiredVerifier;
2394    }
2395
2396    private String getRequiredInstallerLPr() {
2397        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2398        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2399        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2400
2401        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2402                PACKAGE_MIME_TYPE, 0, 0);
2403
2404        String requiredInstaller = null;
2405
2406        final int N = installers.size();
2407        for (int i = 0; i < N; i++) {
2408            final ResolveInfo info = installers.get(i);
2409            final String packageName = info.activityInfo.packageName;
2410
2411            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2412                continue;
2413            }
2414
2415            if (requiredInstaller != null) {
2416                throw new RuntimeException("There must be one required installer");
2417            }
2418
2419            requiredInstaller = packageName;
2420        }
2421
2422        if (requiredInstaller == null) {
2423            throw new RuntimeException("There must be one required installer");
2424        }
2425
2426        return requiredInstaller;
2427    }
2428
2429    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2430        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2431        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2432                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2433
2434        ComponentName verifierComponentName = null;
2435
2436        int priority = -1000;
2437        final int N = receivers.size();
2438        for (int i = 0; i < N; i++) {
2439            final ResolveInfo info = receivers.get(i);
2440
2441            if (info.activityInfo == null) {
2442                continue;
2443            }
2444
2445            final String packageName = info.activityInfo.packageName;
2446
2447            final PackageSetting ps = mSettings.mPackages.get(packageName);
2448            if (ps == null) {
2449                continue;
2450            }
2451
2452            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2453                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2454                continue;
2455            }
2456
2457            // Select the IntentFilterVerifier with the highest priority
2458            if (priority < info.priority) {
2459                priority = info.priority;
2460                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2461                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2462                        + verifierComponentName + " with priority: " + info.priority);
2463            }
2464        }
2465
2466        return verifierComponentName;
2467    }
2468
2469    private void primeDomainVerificationsLPw(int userId) {
2470        if (DEBUG_DOMAIN_VERIFICATION) {
2471            Slog.d(TAG, "Priming domain verifications in user " + userId);
2472        }
2473
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        ArraySet<String> packages = systemConfig.getLinkedApps();
2476        ArraySet<String> domains = new ArraySet<String>();
2477
2478        for (String packageName : packages) {
2479            PackageParser.Package pkg = mPackages.get(packageName);
2480            if (pkg != null) {
2481                if (!pkg.isSystemApp()) {
2482                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2483                    continue;
2484                }
2485
2486                domains.clear();
2487                for (PackageParser.Activity a : pkg.activities) {
2488                    for (ActivityIntentInfo filter : a.intents) {
2489                        if (hasValidDomains(filter)) {
2490                            domains.addAll(filter.getHostsList());
2491                        }
2492                    }
2493                }
2494
2495                if (domains.size() > 0) {
2496                    if (DEBUG_DOMAIN_VERIFICATION) {
2497                        Slog.v(TAG, "      + " + packageName);
2498                    }
2499                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2500                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2501                    // and then 'always' in the per-user state actually used for intent resolution.
2502                    final IntentFilterVerificationInfo ivi;
2503                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2504                            new ArrayList<String>(domains));
2505                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2506                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2507                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2508                } else {
2509                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2510                            + "' does not handle web links");
2511                }
2512            } else {
2513                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2514            }
2515        }
2516
2517        scheduleWritePackageRestrictionsLocked(userId);
2518        scheduleWriteSettingsLocked();
2519    }
2520
2521    private void applyFactoryDefaultBrowserLPw(int userId) {
2522        // The default browser app's package name is stored in a string resource,
2523        // with a product-specific overlay used for vendor customization.
2524        String browserPkg = mContext.getResources().getString(
2525                com.android.internal.R.string.default_browser);
2526        if (!TextUtils.isEmpty(browserPkg)) {
2527            // non-empty string => required to be a known package
2528            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2529            if (ps == null) {
2530                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2531                browserPkg = null;
2532            } else {
2533                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2534            }
2535        }
2536
2537        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2538        // default.  If there's more than one, just leave everything alone.
2539        if (browserPkg == null) {
2540            calculateDefaultBrowserLPw(userId);
2541        }
2542    }
2543
2544    private void calculateDefaultBrowserLPw(int userId) {
2545        List<String> allBrowsers = resolveAllBrowserApps(userId);
2546        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2547        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2548    }
2549
2550    private List<String> resolveAllBrowserApps(int userId) {
2551        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2552        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2553                PackageManager.MATCH_ALL, userId);
2554
2555        final int count = list.size();
2556        List<String> result = new ArrayList<String>(count);
2557        for (int i=0; i<count; i++) {
2558            ResolveInfo info = list.get(i);
2559            if (info.activityInfo == null
2560                    || !info.handleAllWebDataURI
2561                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2562                    || result.contains(info.activityInfo.packageName)) {
2563                continue;
2564            }
2565            result.add(info.activityInfo.packageName);
2566        }
2567
2568        return result;
2569    }
2570
2571    private boolean packageIsBrowser(String packageName, int userId) {
2572        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2573                PackageManager.MATCH_ALL, userId);
2574        final int N = list.size();
2575        for (int i = 0; i < N; i++) {
2576            ResolveInfo info = list.get(i);
2577            if (packageName.equals(info.activityInfo.packageName)) {
2578                return true;
2579            }
2580        }
2581        return false;
2582    }
2583
2584    private void checkDefaultBrowser() {
2585        final int myUserId = UserHandle.myUserId();
2586        final String packageName = getDefaultBrowserPackageName(myUserId);
2587        if (packageName != null) {
2588            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2589            if (info == null) {
2590                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2591                synchronized (mPackages) {
2592                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2593                }
2594            }
2595        }
2596    }
2597
2598    @Override
2599    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2600            throws RemoteException {
2601        try {
2602            return super.onTransact(code, data, reply, flags);
2603        } catch (RuntimeException e) {
2604            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2605                Slog.wtf(TAG, "Package Manager Crash", e);
2606            }
2607            throw e;
2608        }
2609    }
2610
2611    void cleanupInstallFailedPackage(PackageSetting ps) {
2612        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2613
2614        removeDataDirsLI(ps.volumeUuid, ps.name);
2615        if (ps.codePath != null) {
2616            if (ps.codePath.isDirectory()) {
2617                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2618            } else {
2619                ps.codePath.delete();
2620            }
2621        }
2622        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2623            if (ps.resourcePath.isDirectory()) {
2624                FileUtils.deleteContents(ps.resourcePath);
2625            }
2626            ps.resourcePath.delete();
2627        }
2628        mSettings.removePackageLPw(ps.name);
2629    }
2630
2631    static int[] appendInts(int[] cur, int[] add) {
2632        if (add == null) return cur;
2633        if (cur == null) return add;
2634        final int N = add.length;
2635        for (int i=0; i<N; i++) {
2636            cur = appendInt(cur, add[i]);
2637        }
2638        return cur;
2639    }
2640
2641    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        final PackageSetting ps = (PackageSetting) p.mExtras;
2644        if (ps == null) {
2645            return null;
2646        }
2647
2648        final PermissionsState permissionsState = ps.getPermissionsState();
2649
2650        final int[] gids = permissionsState.computeGids(userId);
2651        final Set<String> permissions = permissionsState.getPermissions(userId);
2652        final PackageUserState state = ps.readUserState(userId);
2653
2654        return PackageParser.generatePackageInfo(p, gids, flags,
2655                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2656    }
2657
2658    @Override
2659    public boolean isPackageFrozen(String packageName) {
2660        synchronized (mPackages) {
2661            final PackageSetting ps = mSettings.mPackages.get(packageName);
2662            if (ps != null) {
2663                return ps.frozen;
2664            }
2665        }
2666        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2667        return true;
2668    }
2669
2670    @Override
2671    public boolean isPackageAvailable(String packageName, int userId) {
2672        if (!sUserManager.exists(userId)) return false;
2673        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2674        synchronized (mPackages) {
2675            PackageParser.Package p = mPackages.get(packageName);
2676            if (p != null) {
2677                final PackageSetting ps = (PackageSetting) p.mExtras;
2678                if (ps != null) {
2679                    final PackageUserState state = ps.readUserState(userId);
2680                    if (state != null) {
2681                        return PackageParser.isAvailable(state);
2682                    }
2683                }
2684            }
2685        }
2686        return false;
2687    }
2688
2689    @Override
2690    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2691        if (!sUserManager.exists(userId)) return null;
2692        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2693        // reader
2694        synchronized (mPackages) {
2695            PackageParser.Package p = mPackages.get(packageName);
2696            if (DEBUG_PACKAGE_INFO)
2697                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2698            if (p != null) {
2699                return generatePackageInfo(p, flags, userId);
2700            }
2701            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2702                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2703            }
2704        }
2705        return null;
2706    }
2707
2708    @Override
2709    public String[] currentToCanonicalPackageNames(String[] names) {
2710        String[] out = new String[names.length];
2711        // reader
2712        synchronized (mPackages) {
2713            for (int i=names.length-1; i>=0; i--) {
2714                PackageSetting ps = mSettings.mPackages.get(names[i]);
2715                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2716            }
2717        }
2718        return out;
2719    }
2720
2721    @Override
2722    public String[] canonicalToCurrentPackageNames(String[] names) {
2723        String[] out = new String[names.length];
2724        // reader
2725        synchronized (mPackages) {
2726            for (int i=names.length-1; i>=0; i--) {
2727                String cur = mSettings.mRenamedPackages.get(names[i]);
2728                out[i] = cur != null ? cur : names[i];
2729            }
2730        }
2731        return out;
2732    }
2733
2734    @Override
2735    public int getPackageUid(String packageName, int userId) {
2736        if (!sUserManager.exists(userId)) return -1;
2737        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2738
2739        // reader
2740        synchronized (mPackages) {
2741            PackageParser.Package p = mPackages.get(packageName);
2742            if(p != null) {
2743                return UserHandle.getUid(userId, p.applicationInfo.uid);
2744            }
2745            PackageSetting ps = mSettings.mPackages.get(packageName);
2746            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2747                return -1;
2748            }
2749            p = ps.pkg;
2750            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2751        }
2752    }
2753
2754    @Override
2755    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2756        if (!sUserManager.exists(userId)) {
2757            return null;
2758        }
2759
2760        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2761                "getPackageGids");
2762
2763        // reader
2764        synchronized (mPackages) {
2765            PackageParser.Package p = mPackages.get(packageName);
2766            if (DEBUG_PACKAGE_INFO) {
2767                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2768            }
2769            if (p != null) {
2770                PackageSetting ps = (PackageSetting) p.mExtras;
2771                return ps.getPermissionsState().computeGids(userId);
2772            }
2773        }
2774
2775        return null;
2776    }
2777
2778    static PermissionInfo generatePermissionInfo(
2779            BasePermission bp, int flags) {
2780        if (bp.perm != null) {
2781            return PackageParser.generatePermissionInfo(bp.perm, flags);
2782        }
2783        PermissionInfo pi = new PermissionInfo();
2784        pi.name = bp.name;
2785        pi.packageName = bp.sourcePackage;
2786        pi.nonLocalizedLabel = bp.name;
2787        pi.protectionLevel = bp.protectionLevel;
2788        return pi;
2789    }
2790
2791    @Override
2792    public PermissionInfo getPermissionInfo(String name, int flags) {
2793        // reader
2794        synchronized (mPackages) {
2795            final BasePermission p = mSettings.mPermissions.get(name);
2796            if (p != null) {
2797                return generatePermissionInfo(p, flags);
2798            }
2799            return null;
2800        }
2801    }
2802
2803    @Override
2804    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2805        // reader
2806        synchronized (mPackages) {
2807            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2808            for (BasePermission p : mSettings.mPermissions.values()) {
2809                if (group == null) {
2810                    if (p.perm == null || p.perm.info.group == null) {
2811                        out.add(generatePermissionInfo(p, flags));
2812                    }
2813                } else {
2814                    if (p.perm != null && group.equals(p.perm.info.group)) {
2815                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2816                    }
2817                }
2818            }
2819
2820            if (out.size() > 0) {
2821                return out;
2822            }
2823            return mPermissionGroups.containsKey(group) ? out : null;
2824        }
2825    }
2826
2827    @Override
2828    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2829        // reader
2830        synchronized (mPackages) {
2831            return PackageParser.generatePermissionGroupInfo(
2832                    mPermissionGroups.get(name), flags);
2833        }
2834    }
2835
2836    @Override
2837    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2838        // reader
2839        synchronized (mPackages) {
2840            final int N = mPermissionGroups.size();
2841            ArrayList<PermissionGroupInfo> out
2842                    = new ArrayList<PermissionGroupInfo>(N);
2843            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2844                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2845            }
2846            return out;
2847        }
2848    }
2849
2850    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2851            int userId) {
2852        if (!sUserManager.exists(userId)) return null;
2853        PackageSetting ps = mSettings.mPackages.get(packageName);
2854        if (ps != null) {
2855            if (ps.pkg == null) {
2856                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2857                        flags, userId);
2858                if (pInfo != null) {
2859                    return pInfo.applicationInfo;
2860                }
2861                return null;
2862            }
2863            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2864                    ps.readUserState(userId), userId);
2865        }
2866        return null;
2867    }
2868
2869    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2870            int userId) {
2871        if (!sUserManager.exists(userId)) return null;
2872        PackageSetting ps = mSettings.mPackages.get(packageName);
2873        if (ps != null) {
2874            PackageParser.Package pkg = ps.pkg;
2875            if (pkg == null) {
2876                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2877                    return null;
2878                }
2879                // Only data remains, so we aren't worried about code paths
2880                pkg = new PackageParser.Package(packageName);
2881                pkg.applicationInfo.packageName = packageName;
2882                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2883                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2884                pkg.applicationInfo.dataDir = Environment
2885                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2886                        .getAbsolutePath();
2887                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2888                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2889            }
2890            return generatePackageInfo(pkg, flags, userId);
2891        }
2892        return null;
2893    }
2894
2895    @Override
2896    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2897        if (!sUserManager.exists(userId)) return null;
2898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2899        // writer
2900        synchronized (mPackages) {
2901            PackageParser.Package p = mPackages.get(packageName);
2902            if (DEBUG_PACKAGE_INFO) Log.v(
2903                    TAG, "getApplicationInfo " + packageName
2904                    + ": " + p);
2905            if (p != null) {
2906                PackageSetting ps = mSettings.mPackages.get(packageName);
2907                if (ps == null) return null;
2908                // Note: isEnabledLP() does not apply here - always return info
2909                return PackageParser.generateApplicationInfo(
2910                        p, flags, ps.readUserState(userId), userId);
2911            }
2912            if ("android".equals(packageName)||"system".equals(packageName)) {
2913                return mAndroidApplication;
2914            }
2915            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2916                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2917            }
2918        }
2919        return null;
2920    }
2921
2922    @Override
2923    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2924            final IPackageDataObserver observer) {
2925        mContext.enforceCallingOrSelfPermission(
2926                android.Manifest.permission.CLEAR_APP_CACHE, null);
2927        // Queue up an async operation since clearing cache may take a little while.
2928        mHandler.post(new Runnable() {
2929            public void run() {
2930                mHandler.removeCallbacks(this);
2931                int retCode = -1;
2932                synchronized (mInstallLock) {
2933                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2934                    if (retCode < 0) {
2935                        Slog.w(TAG, "Couldn't clear application caches");
2936                    }
2937                }
2938                if (observer != null) {
2939                    try {
2940                        observer.onRemoveCompleted(null, (retCode >= 0));
2941                    } catch (RemoteException e) {
2942                        Slog.w(TAG, "RemoveException when invoking call back");
2943                    }
2944                }
2945            }
2946        });
2947    }
2948
2949    @Override
2950    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2951            final IntentSender pi) {
2952        mContext.enforceCallingOrSelfPermission(
2953                android.Manifest.permission.CLEAR_APP_CACHE, null);
2954        // Queue up an async operation since clearing cache may take a little while.
2955        mHandler.post(new Runnable() {
2956            public void run() {
2957                mHandler.removeCallbacks(this);
2958                int retCode = -1;
2959                synchronized (mInstallLock) {
2960                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2961                    if (retCode < 0) {
2962                        Slog.w(TAG, "Couldn't clear application caches");
2963                    }
2964                }
2965                if(pi != null) {
2966                    try {
2967                        // Callback via pending intent
2968                        int code = (retCode >= 0) ? 1 : 0;
2969                        pi.sendIntent(null, code, null,
2970                                null, null);
2971                    } catch (SendIntentException e1) {
2972                        Slog.i(TAG, "Failed to send pending intent");
2973                    }
2974                }
2975            }
2976        });
2977    }
2978
2979    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2980        synchronized (mInstallLock) {
2981            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2982                throw new IOException("Failed to free enough space");
2983            }
2984        }
2985    }
2986
2987    @Override
2988    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2989        if (!sUserManager.exists(userId)) return null;
2990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2991        synchronized (mPackages) {
2992            PackageParser.Activity a = mActivities.mActivities.get(component);
2993
2994            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2995            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2996                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2997                if (ps == null) return null;
2998                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2999                        userId);
3000            }
3001            if (mResolveComponentName.equals(component)) {
3002                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3003                        new PackageUserState(), userId);
3004            }
3005        }
3006        return null;
3007    }
3008
3009    @Override
3010    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3011            String resolvedType) {
3012        synchronized (mPackages) {
3013            if (component.equals(mResolveComponentName)) {
3014                // The resolver supports EVERYTHING!
3015                return true;
3016            }
3017            PackageParser.Activity a = mActivities.mActivities.get(component);
3018            if (a == null) {
3019                return false;
3020            }
3021            for (int i=0; i<a.intents.size(); i++) {
3022                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3023                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3024                    return true;
3025                }
3026            }
3027            return false;
3028        }
3029    }
3030
3031    @Override
3032    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3035        synchronized (mPackages) {
3036            PackageParser.Activity a = mReceivers.mActivities.get(component);
3037            if (DEBUG_PACKAGE_INFO) Log.v(
3038                TAG, "getReceiverInfo " + component + ": " + a);
3039            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3040                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3041                if (ps == null) return null;
3042                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3043                        userId);
3044            }
3045        }
3046        return null;
3047    }
3048
3049    @Override
3050    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3051        if (!sUserManager.exists(userId)) return null;
3052        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3053        synchronized (mPackages) {
3054            PackageParser.Service s = mServices.mServices.get(component);
3055            if (DEBUG_PACKAGE_INFO) Log.v(
3056                TAG, "getServiceInfo " + component + ": " + s);
3057            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3058                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3059                if (ps == null) return null;
3060                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3061                        userId);
3062            }
3063        }
3064        return null;
3065    }
3066
3067    @Override
3068    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3069        if (!sUserManager.exists(userId)) return null;
3070        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3071        synchronized (mPackages) {
3072            PackageParser.Provider p = mProviders.mProviders.get(component);
3073            if (DEBUG_PACKAGE_INFO) Log.v(
3074                TAG, "getProviderInfo " + component + ": " + p);
3075            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3076                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3077                if (ps == null) return null;
3078                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3079                        userId);
3080            }
3081        }
3082        return null;
3083    }
3084
3085    @Override
3086    public String[] getSystemSharedLibraryNames() {
3087        Set<String> libSet;
3088        synchronized (mPackages) {
3089            libSet = mSharedLibraries.keySet();
3090            int size = libSet.size();
3091            if (size > 0) {
3092                String[] libs = new String[size];
3093                libSet.toArray(libs);
3094                return libs;
3095            }
3096        }
3097        return null;
3098    }
3099
3100    /**
3101     * @hide
3102     */
3103    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3104        synchronized (mPackages) {
3105            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3106            if (lib != null && lib.apk != null) {
3107                return mPackages.get(lib.apk);
3108            }
3109        }
3110        return null;
3111    }
3112
3113    @Override
3114    public FeatureInfo[] getSystemAvailableFeatures() {
3115        Collection<FeatureInfo> featSet;
3116        synchronized (mPackages) {
3117            featSet = mAvailableFeatures.values();
3118            int size = featSet.size();
3119            if (size > 0) {
3120                FeatureInfo[] features = new FeatureInfo[size+1];
3121                featSet.toArray(features);
3122                FeatureInfo fi = new FeatureInfo();
3123                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3124                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3125                features[size] = fi;
3126                return features;
3127            }
3128        }
3129        return null;
3130    }
3131
3132    @Override
3133    public boolean hasSystemFeature(String name) {
3134        synchronized (mPackages) {
3135            return mAvailableFeatures.containsKey(name);
3136        }
3137    }
3138
3139    private void checkValidCaller(int uid, int userId) {
3140        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3141            return;
3142
3143        throw new SecurityException("Caller uid=" + uid
3144                + " is not privileged to communicate with user=" + userId);
3145    }
3146
3147    @Override
3148    public int checkPermission(String permName, String pkgName, int userId) {
3149        if (!sUserManager.exists(userId)) {
3150            return PackageManager.PERMISSION_DENIED;
3151        }
3152
3153        synchronized (mPackages) {
3154            final PackageParser.Package p = mPackages.get(pkgName);
3155            if (p != null && p.mExtras != null) {
3156                final PackageSetting ps = (PackageSetting) p.mExtras;
3157                final PermissionsState permissionsState = ps.getPermissionsState();
3158                if (permissionsState.hasPermission(permName, userId)) {
3159                    return PackageManager.PERMISSION_GRANTED;
3160                }
3161                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3162                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3163                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3164                    return PackageManager.PERMISSION_GRANTED;
3165                }
3166            }
3167        }
3168
3169        return PackageManager.PERMISSION_DENIED;
3170    }
3171
3172    @Override
3173    public int checkUidPermission(String permName, int uid) {
3174        final int userId = UserHandle.getUserId(uid);
3175
3176        if (!sUserManager.exists(userId)) {
3177            return PackageManager.PERMISSION_DENIED;
3178        }
3179
3180        synchronized (mPackages) {
3181            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3182            if (obj != null) {
3183                final SettingBase ps = (SettingBase) obj;
3184                final PermissionsState permissionsState = ps.getPermissionsState();
3185                if (permissionsState.hasPermission(permName, userId)) {
3186                    return PackageManager.PERMISSION_GRANTED;
3187                }
3188                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3189                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3190                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3191                    return PackageManager.PERMISSION_GRANTED;
3192                }
3193            } else {
3194                ArraySet<String> perms = mSystemPermissions.get(uid);
3195                if (perms != null) {
3196                    if (perms.contains(permName)) {
3197                        return PackageManager.PERMISSION_GRANTED;
3198                    }
3199                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3200                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3201                        return PackageManager.PERMISSION_GRANTED;
3202                    }
3203                }
3204            }
3205        }
3206
3207        return PackageManager.PERMISSION_DENIED;
3208    }
3209
3210    @Override
3211    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3212        if (UserHandle.getCallingUserId() != userId) {
3213            mContext.enforceCallingPermission(
3214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3215                    "isPermissionRevokedByPolicy for user " + userId);
3216        }
3217
3218        if (checkPermission(permission, packageName, userId)
3219                == PackageManager.PERMISSION_GRANTED) {
3220            return false;
3221        }
3222
3223        final long identity = Binder.clearCallingIdentity();
3224        try {
3225            final int flags = getPermissionFlags(permission, packageName, userId);
3226            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3227        } finally {
3228            Binder.restoreCallingIdentity(identity);
3229        }
3230    }
3231
3232    @Override
3233    public String getPermissionControllerPackageName() {
3234        synchronized (mPackages) {
3235            return mRequiredInstallerPackage;
3236        }
3237    }
3238
3239    /**
3240     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3241     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3242     * @param checkShell TODO(yamasani):
3243     * @param message the message to log on security exception
3244     */
3245    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3246            boolean checkShell, String message) {
3247        if (userId < 0) {
3248            throw new IllegalArgumentException("Invalid userId " + userId);
3249        }
3250        if (checkShell) {
3251            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3252        }
3253        if (userId == UserHandle.getUserId(callingUid)) return;
3254        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3255            if (requireFullPermission) {
3256                mContext.enforceCallingOrSelfPermission(
3257                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3258            } else {
3259                try {
3260                    mContext.enforceCallingOrSelfPermission(
3261                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3262                } catch (SecurityException se) {
3263                    mContext.enforceCallingOrSelfPermission(
3264                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3265                }
3266            }
3267        }
3268    }
3269
3270    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3271        if (callingUid == Process.SHELL_UID) {
3272            if (userHandle >= 0
3273                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3274                throw new SecurityException("Shell does not have permission to access user "
3275                        + userHandle);
3276            } else if (userHandle < 0) {
3277                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3278                        + Debug.getCallers(3));
3279            }
3280        }
3281    }
3282
3283    private BasePermission findPermissionTreeLP(String permName) {
3284        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3285            if (permName.startsWith(bp.name) &&
3286                    permName.length() > bp.name.length() &&
3287                    permName.charAt(bp.name.length()) == '.') {
3288                return bp;
3289            }
3290        }
3291        return null;
3292    }
3293
3294    private BasePermission checkPermissionTreeLP(String permName) {
3295        if (permName != null) {
3296            BasePermission bp = findPermissionTreeLP(permName);
3297            if (bp != null) {
3298                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3299                    return bp;
3300                }
3301                throw new SecurityException("Calling uid "
3302                        + Binder.getCallingUid()
3303                        + " is not allowed to add to permission tree "
3304                        + bp.name + " owned by uid " + bp.uid);
3305            }
3306        }
3307        throw new SecurityException("No permission tree found for " + permName);
3308    }
3309
3310    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3311        if (s1 == null) {
3312            return s2 == null;
3313        }
3314        if (s2 == null) {
3315            return false;
3316        }
3317        if (s1.getClass() != s2.getClass()) {
3318            return false;
3319        }
3320        return s1.equals(s2);
3321    }
3322
3323    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3324        if (pi1.icon != pi2.icon) return false;
3325        if (pi1.logo != pi2.logo) return false;
3326        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3327        if (!compareStrings(pi1.name, pi2.name)) return false;
3328        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3329        // We'll take care of setting this one.
3330        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3331        // These are not currently stored in settings.
3332        //if (!compareStrings(pi1.group, pi2.group)) return false;
3333        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3334        //if (pi1.labelRes != pi2.labelRes) return false;
3335        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3336        return true;
3337    }
3338
3339    int permissionInfoFootprint(PermissionInfo info) {
3340        int size = info.name.length();
3341        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3342        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3343        return size;
3344    }
3345
3346    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3347        int size = 0;
3348        for (BasePermission perm : mSettings.mPermissions.values()) {
3349            if (perm.uid == tree.uid) {
3350                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3351            }
3352        }
3353        return size;
3354    }
3355
3356    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3357        // We calculate the max size of permissions defined by this uid and throw
3358        // if that plus the size of 'info' would exceed our stated maximum.
3359        if (tree.uid != Process.SYSTEM_UID) {
3360            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3361            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3362                throw new SecurityException("Permission tree size cap exceeded");
3363            }
3364        }
3365    }
3366
3367    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3368        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3369            throw new SecurityException("Label must be specified in permission");
3370        }
3371        BasePermission tree = checkPermissionTreeLP(info.name);
3372        BasePermission bp = mSettings.mPermissions.get(info.name);
3373        boolean added = bp == null;
3374        boolean changed = true;
3375        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3376        if (added) {
3377            enforcePermissionCapLocked(info, tree);
3378            bp = new BasePermission(info.name, tree.sourcePackage,
3379                    BasePermission.TYPE_DYNAMIC);
3380        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3381            throw new SecurityException(
3382                    "Not allowed to modify non-dynamic permission "
3383                    + info.name);
3384        } else {
3385            if (bp.protectionLevel == fixedLevel
3386                    && bp.perm.owner.equals(tree.perm.owner)
3387                    && bp.uid == tree.uid
3388                    && comparePermissionInfos(bp.perm.info, info)) {
3389                changed = false;
3390            }
3391        }
3392        bp.protectionLevel = fixedLevel;
3393        info = new PermissionInfo(info);
3394        info.protectionLevel = fixedLevel;
3395        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3396        bp.perm.info.packageName = tree.perm.info.packageName;
3397        bp.uid = tree.uid;
3398        if (added) {
3399            mSettings.mPermissions.put(info.name, bp);
3400        }
3401        if (changed) {
3402            if (!async) {
3403                mSettings.writeLPr();
3404            } else {
3405                scheduleWriteSettingsLocked();
3406            }
3407        }
3408        return added;
3409    }
3410
3411    @Override
3412    public boolean addPermission(PermissionInfo info) {
3413        synchronized (mPackages) {
3414            return addPermissionLocked(info, false);
3415        }
3416    }
3417
3418    @Override
3419    public boolean addPermissionAsync(PermissionInfo info) {
3420        synchronized (mPackages) {
3421            return addPermissionLocked(info, true);
3422        }
3423    }
3424
3425    @Override
3426    public void removePermission(String name) {
3427        synchronized (mPackages) {
3428            checkPermissionTreeLP(name);
3429            BasePermission bp = mSettings.mPermissions.get(name);
3430            if (bp != null) {
3431                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3432                    throw new SecurityException(
3433                            "Not allowed to modify non-dynamic permission "
3434                            + name);
3435                }
3436                mSettings.mPermissions.remove(name);
3437                mSettings.writeLPr();
3438            }
3439        }
3440    }
3441
3442    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3443            BasePermission bp) {
3444        int index = pkg.requestedPermissions.indexOf(bp.name);
3445        if (index == -1) {
3446            throw new SecurityException("Package " + pkg.packageName
3447                    + " has not requested permission " + bp.name);
3448        }
3449        if (!bp.isRuntime() && !bp.isDevelopment()) {
3450            throw new SecurityException("Permission " + bp.name
3451                    + " is not a changeable permission type");
3452        }
3453    }
3454
3455    @Override
3456    public void grantRuntimePermission(String packageName, String name, final int userId) {
3457        if (!sUserManager.exists(userId)) {
3458            Log.e(TAG, "No such user:" + userId);
3459            return;
3460        }
3461
3462        mContext.enforceCallingOrSelfPermission(
3463                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3464                "grantRuntimePermission");
3465
3466        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3467                "grantRuntimePermission");
3468
3469        final int uid;
3470        final SettingBase sb;
3471
3472        synchronized (mPackages) {
3473            final PackageParser.Package pkg = mPackages.get(packageName);
3474            if (pkg == null) {
3475                throw new IllegalArgumentException("Unknown package: " + packageName);
3476            }
3477
3478            final BasePermission bp = mSettings.mPermissions.get(name);
3479            if (bp == null) {
3480                throw new IllegalArgumentException("Unknown permission: " + name);
3481            }
3482
3483            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3484
3485            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3486            sb = (SettingBase) pkg.mExtras;
3487            if (sb == null) {
3488                throw new IllegalArgumentException("Unknown package: " + packageName);
3489            }
3490
3491            final PermissionsState permissionsState = sb.getPermissionsState();
3492
3493            final int flags = permissionsState.getPermissionFlags(name, userId);
3494            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3495                throw new SecurityException("Cannot grant system fixed permission: "
3496                        + name + " for package: " + packageName);
3497            }
3498
3499            if (bp.isDevelopment()) {
3500                // Development permissions must be handled specially, since they are not
3501                // normal runtime permissions.  For now they apply to all users.
3502                if (permissionsState.grantInstallPermission(bp) !=
3503                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3504                    scheduleWriteSettingsLocked();
3505                }
3506                return;
3507            }
3508
3509            final int result = permissionsState.grantRuntimePermission(bp, userId);
3510            switch (result) {
3511                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3512                    return;
3513                }
3514
3515                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3516                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3517                    mHandler.post(new Runnable() {
3518                        @Override
3519                        public void run() {
3520                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3521                        }
3522                    });
3523                }
3524                break;
3525            }
3526
3527            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3528
3529            // Not critical if that is lost - app has to request again.
3530            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3531        }
3532
3533        // Only need to do this if user is initialized. Otherwise it's a new user
3534        // and there are no processes running as the user yet and there's no need
3535        // to make an expensive call to remount processes for the changed permissions.
3536        if (READ_EXTERNAL_STORAGE.equals(name)
3537                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3538            final long token = Binder.clearCallingIdentity();
3539            try {
3540                if (sUserManager.isInitialized(userId)) {
3541                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3542                            MountServiceInternal.class);
3543                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3544                }
3545            } finally {
3546                Binder.restoreCallingIdentity(token);
3547            }
3548        }
3549    }
3550
3551    @Override
3552    public void revokeRuntimePermission(String packageName, String name, int userId) {
3553        if (!sUserManager.exists(userId)) {
3554            Log.e(TAG, "No such user:" + userId);
3555            return;
3556        }
3557
3558        mContext.enforceCallingOrSelfPermission(
3559                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3560                "revokeRuntimePermission");
3561
3562        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3563                "revokeRuntimePermission");
3564
3565        final int appId;
3566
3567        synchronized (mPackages) {
3568            final PackageParser.Package pkg = mPackages.get(packageName);
3569            if (pkg == null) {
3570                throw new IllegalArgumentException("Unknown package: " + packageName);
3571            }
3572
3573            final BasePermission bp = mSettings.mPermissions.get(name);
3574            if (bp == null) {
3575                throw new IllegalArgumentException("Unknown permission: " + name);
3576            }
3577
3578            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3579
3580            SettingBase sb = (SettingBase) pkg.mExtras;
3581            if (sb == null) {
3582                throw new IllegalArgumentException("Unknown package: " + packageName);
3583            }
3584
3585            final PermissionsState permissionsState = sb.getPermissionsState();
3586
3587            final int flags = permissionsState.getPermissionFlags(name, userId);
3588            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3589                throw new SecurityException("Cannot revoke system fixed permission: "
3590                        + name + " for package: " + packageName);
3591            }
3592
3593            if (bp.isDevelopment()) {
3594                // Development permissions must be handled specially, since they are not
3595                // normal runtime permissions.  For now they apply to all users.
3596                if (permissionsState.revokeInstallPermission(bp) !=
3597                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3598                    scheduleWriteSettingsLocked();
3599                }
3600                return;
3601            }
3602
3603            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3604                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3605                return;
3606            }
3607
3608            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3609
3610            // Critical, after this call app should never have the permission.
3611            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3612
3613            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3614        }
3615
3616        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3617    }
3618
3619    @Override
3620    public void resetRuntimePermissions() {
3621        mContext.enforceCallingOrSelfPermission(
3622                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3623                "revokeRuntimePermission");
3624
3625        int callingUid = Binder.getCallingUid();
3626        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3627            mContext.enforceCallingOrSelfPermission(
3628                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3629                    "resetRuntimePermissions");
3630        }
3631
3632        synchronized (mPackages) {
3633            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3634            for (int userId : UserManagerService.getInstance().getUserIds()) {
3635                final int packageCount = mPackages.size();
3636                for (int i = 0; i < packageCount; i++) {
3637                    PackageParser.Package pkg = mPackages.valueAt(i);
3638                    if (!(pkg.mExtras instanceof PackageSetting)) {
3639                        continue;
3640                    }
3641                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3642                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3643                }
3644            }
3645        }
3646    }
3647
3648    @Override
3649    public int getPermissionFlags(String name, String packageName, int userId) {
3650        if (!sUserManager.exists(userId)) {
3651            return 0;
3652        }
3653
3654        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3655
3656        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3657                "getPermissionFlags");
3658
3659        synchronized (mPackages) {
3660            final PackageParser.Package pkg = mPackages.get(packageName);
3661            if (pkg == null) {
3662                throw new IllegalArgumentException("Unknown package: " + packageName);
3663            }
3664
3665            final BasePermission bp = mSettings.mPermissions.get(name);
3666            if (bp == null) {
3667                throw new IllegalArgumentException("Unknown permission: " + name);
3668            }
3669
3670            SettingBase sb = (SettingBase) pkg.mExtras;
3671            if (sb == null) {
3672                throw new IllegalArgumentException("Unknown package: " + packageName);
3673            }
3674
3675            PermissionsState permissionsState = sb.getPermissionsState();
3676            return permissionsState.getPermissionFlags(name, userId);
3677        }
3678    }
3679
3680    @Override
3681    public void updatePermissionFlags(String name, String packageName, int flagMask,
3682            int flagValues, int userId) {
3683        if (!sUserManager.exists(userId)) {
3684            return;
3685        }
3686
3687        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3688
3689        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3690                "updatePermissionFlags");
3691
3692        // Only the system can change these flags and nothing else.
3693        if (getCallingUid() != Process.SYSTEM_UID) {
3694            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3695            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3696            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3697            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3698        }
3699
3700        synchronized (mPackages) {
3701            final PackageParser.Package pkg = mPackages.get(packageName);
3702            if (pkg == null) {
3703                throw new IllegalArgumentException("Unknown package: " + packageName);
3704            }
3705
3706            final BasePermission bp = mSettings.mPermissions.get(name);
3707            if (bp == null) {
3708                throw new IllegalArgumentException("Unknown permission: " + name);
3709            }
3710
3711            SettingBase sb = (SettingBase) pkg.mExtras;
3712            if (sb == null) {
3713                throw new IllegalArgumentException("Unknown package: " + packageName);
3714            }
3715
3716            PermissionsState permissionsState = sb.getPermissionsState();
3717
3718            // Only the package manager can change flags for system component permissions.
3719            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3720            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3721                return;
3722            }
3723
3724            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3725
3726            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3727                // Install and runtime permissions are stored in different places,
3728                // so figure out what permission changed and persist the change.
3729                if (permissionsState.getInstallPermissionState(name) != null) {
3730                    scheduleWriteSettingsLocked();
3731                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3732                        || hadState) {
3733                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3734                }
3735            }
3736        }
3737    }
3738
3739    /**
3740     * Update the permission flags for all packages and runtime permissions of a user in order
3741     * to allow device or profile owner to remove POLICY_FIXED.
3742     */
3743    @Override
3744    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3745        if (!sUserManager.exists(userId)) {
3746            return;
3747        }
3748
3749        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3750
3751        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3752                "updatePermissionFlagsForAllApps");
3753
3754        // Only the system can change system fixed flags.
3755        if (getCallingUid() != Process.SYSTEM_UID) {
3756            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3757            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3758        }
3759
3760        synchronized (mPackages) {
3761            boolean changed = false;
3762            final int packageCount = mPackages.size();
3763            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3764                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3765                SettingBase sb = (SettingBase) pkg.mExtras;
3766                if (sb == null) {
3767                    continue;
3768                }
3769                PermissionsState permissionsState = sb.getPermissionsState();
3770                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3771                        userId, flagMask, flagValues);
3772            }
3773            if (changed) {
3774                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3775            }
3776        }
3777    }
3778
3779    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3780        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3781                != PackageManager.PERMISSION_GRANTED
3782            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3783                != PackageManager.PERMISSION_GRANTED) {
3784            throw new SecurityException(message + " requires "
3785                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3786                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3787        }
3788    }
3789
3790    @Override
3791    public boolean shouldShowRequestPermissionRationale(String permissionName,
3792            String packageName, int userId) {
3793        if (UserHandle.getCallingUserId() != userId) {
3794            mContext.enforceCallingPermission(
3795                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3796                    "canShowRequestPermissionRationale for user " + userId);
3797        }
3798
3799        final int uid = getPackageUid(packageName, userId);
3800        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3801            return false;
3802        }
3803
3804        if (checkPermission(permissionName, packageName, userId)
3805                == PackageManager.PERMISSION_GRANTED) {
3806            return false;
3807        }
3808
3809        final int flags;
3810
3811        final long identity = Binder.clearCallingIdentity();
3812        try {
3813            flags = getPermissionFlags(permissionName,
3814                    packageName, userId);
3815        } finally {
3816            Binder.restoreCallingIdentity(identity);
3817        }
3818
3819        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3820                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3821                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3822
3823        if ((flags & fixedFlags) != 0) {
3824            return false;
3825        }
3826
3827        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3828    }
3829
3830    @Override
3831    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3832        mContext.enforceCallingOrSelfPermission(
3833                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3834                "addOnPermissionsChangeListener");
3835
3836        synchronized (mPackages) {
3837            mOnPermissionChangeListeners.addListenerLocked(listener);
3838        }
3839    }
3840
3841    @Override
3842    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3843        synchronized (mPackages) {
3844            mOnPermissionChangeListeners.removeListenerLocked(listener);
3845        }
3846    }
3847
3848    @Override
3849    public boolean isProtectedBroadcast(String actionName) {
3850        synchronized (mPackages) {
3851            return mProtectedBroadcasts.contains(actionName);
3852        }
3853    }
3854
3855    @Override
3856    public int checkSignatures(String pkg1, String pkg2) {
3857        synchronized (mPackages) {
3858            final PackageParser.Package p1 = mPackages.get(pkg1);
3859            final PackageParser.Package p2 = mPackages.get(pkg2);
3860            if (p1 == null || p1.mExtras == null
3861                    || p2 == null || p2.mExtras == null) {
3862                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3863            }
3864            return compareSignatures(p1.mSignatures, p2.mSignatures);
3865        }
3866    }
3867
3868    @Override
3869    public int checkUidSignatures(int uid1, int uid2) {
3870        // Map to base uids.
3871        uid1 = UserHandle.getAppId(uid1);
3872        uid2 = UserHandle.getAppId(uid2);
3873        // reader
3874        synchronized (mPackages) {
3875            Signature[] s1;
3876            Signature[] s2;
3877            Object obj = mSettings.getUserIdLPr(uid1);
3878            if (obj != null) {
3879                if (obj instanceof SharedUserSetting) {
3880                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3881                } else if (obj instanceof PackageSetting) {
3882                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3883                } else {
3884                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885                }
3886            } else {
3887                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3888            }
3889            obj = mSettings.getUserIdLPr(uid2);
3890            if (obj != null) {
3891                if (obj instanceof SharedUserSetting) {
3892                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3893                } else if (obj instanceof PackageSetting) {
3894                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3895                } else {
3896                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897                }
3898            } else {
3899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900            }
3901            return compareSignatures(s1, s2);
3902        }
3903    }
3904
3905    private void killUid(int appId, int userId, String reason) {
3906        final long identity = Binder.clearCallingIdentity();
3907        try {
3908            IActivityManager am = ActivityManagerNative.getDefault();
3909            if (am != null) {
3910                try {
3911                    am.killUid(appId, userId, reason);
3912                } catch (RemoteException e) {
3913                    /* ignore - same process */
3914                }
3915            }
3916        } finally {
3917            Binder.restoreCallingIdentity(identity);
3918        }
3919    }
3920
3921    /**
3922     * Compares two sets of signatures. Returns:
3923     * <br />
3924     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3925     * <br />
3926     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3927     * <br />
3928     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3929     * <br />
3930     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3931     * <br />
3932     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3933     */
3934    static int compareSignatures(Signature[] s1, Signature[] s2) {
3935        if (s1 == null) {
3936            return s2 == null
3937                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3938                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3939        }
3940
3941        if (s2 == null) {
3942            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3943        }
3944
3945        if (s1.length != s2.length) {
3946            return PackageManager.SIGNATURE_NO_MATCH;
3947        }
3948
3949        // Since both signature sets are of size 1, we can compare without HashSets.
3950        if (s1.length == 1) {
3951            return s1[0].equals(s2[0]) ?
3952                    PackageManager.SIGNATURE_MATCH :
3953                    PackageManager.SIGNATURE_NO_MATCH;
3954        }
3955
3956        ArraySet<Signature> set1 = new ArraySet<Signature>();
3957        for (Signature sig : s1) {
3958            set1.add(sig);
3959        }
3960        ArraySet<Signature> set2 = new ArraySet<Signature>();
3961        for (Signature sig : s2) {
3962            set2.add(sig);
3963        }
3964        // Make sure s2 contains all signatures in s1.
3965        if (set1.equals(set2)) {
3966            return PackageManager.SIGNATURE_MATCH;
3967        }
3968        return PackageManager.SIGNATURE_NO_MATCH;
3969    }
3970
3971    /**
3972     * If the database version for this type of package (internal storage or
3973     * external storage) is less than the version where package signatures
3974     * were updated, return true.
3975     */
3976    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3977        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3978        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3979    }
3980
3981    /**
3982     * Used for backward compatibility to make sure any packages with
3983     * certificate chains get upgraded to the new style. {@code existingSigs}
3984     * will be in the old format (since they were stored on disk from before the
3985     * system upgrade) and {@code scannedSigs} will be in the newer format.
3986     */
3987    private int compareSignaturesCompat(PackageSignatures existingSigs,
3988            PackageParser.Package scannedPkg) {
3989        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3990            return PackageManager.SIGNATURE_NO_MATCH;
3991        }
3992
3993        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3994        for (Signature sig : existingSigs.mSignatures) {
3995            existingSet.add(sig);
3996        }
3997        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3998        for (Signature sig : scannedPkg.mSignatures) {
3999            try {
4000                Signature[] chainSignatures = sig.getChainSignatures();
4001                for (Signature chainSig : chainSignatures) {
4002                    scannedCompatSet.add(chainSig);
4003                }
4004            } catch (CertificateEncodingException e) {
4005                scannedCompatSet.add(sig);
4006            }
4007        }
4008        /*
4009         * Make sure the expanded scanned set contains all signatures in the
4010         * existing one.
4011         */
4012        if (scannedCompatSet.equals(existingSet)) {
4013            // Migrate the old signatures to the new scheme.
4014            existingSigs.assignSignatures(scannedPkg.mSignatures);
4015            // The new KeySets will be re-added later in the scanning process.
4016            synchronized (mPackages) {
4017                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4018            }
4019            return PackageManager.SIGNATURE_MATCH;
4020        }
4021        return PackageManager.SIGNATURE_NO_MATCH;
4022    }
4023
4024    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4025        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4026        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4027    }
4028
4029    private int compareSignaturesRecover(PackageSignatures existingSigs,
4030            PackageParser.Package scannedPkg) {
4031        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4032            return PackageManager.SIGNATURE_NO_MATCH;
4033        }
4034
4035        String msg = null;
4036        try {
4037            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4038                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4039                        + scannedPkg.packageName);
4040                return PackageManager.SIGNATURE_MATCH;
4041            }
4042        } catch (CertificateException e) {
4043            msg = e.getMessage();
4044        }
4045
4046        logCriticalInfo(Log.INFO,
4047                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4048        return PackageManager.SIGNATURE_NO_MATCH;
4049    }
4050
4051    @Override
4052    public String[] getPackagesForUid(int uid) {
4053        uid = UserHandle.getAppId(uid);
4054        // reader
4055        synchronized (mPackages) {
4056            Object obj = mSettings.getUserIdLPr(uid);
4057            if (obj instanceof SharedUserSetting) {
4058                final SharedUserSetting sus = (SharedUserSetting) obj;
4059                final int N = sus.packages.size();
4060                final String[] res = new String[N];
4061                final Iterator<PackageSetting> it = sus.packages.iterator();
4062                int i = 0;
4063                while (it.hasNext()) {
4064                    res[i++] = it.next().name;
4065                }
4066                return res;
4067            } else if (obj instanceof PackageSetting) {
4068                final PackageSetting ps = (PackageSetting) obj;
4069                return new String[] { ps.name };
4070            }
4071        }
4072        return null;
4073    }
4074
4075    @Override
4076    public String getNameForUid(int uid) {
4077        // reader
4078        synchronized (mPackages) {
4079            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4080            if (obj instanceof SharedUserSetting) {
4081                final SharedUserSetting sus = (SharedUserSetting) obj;
4082                return sus.name + ":" + sus.userId;
4083            } else if (obj instanceof PackageSetting) {
4084                final PackageSetting ps = (PackageSetting) obj;
4085                return ps.name;
4086            }
4087        }
4088        return null;
4089    }
4090
4091    @Override
4092    public int getUidForSharedUser(String sharedUserName) {
4093        if(sharedUserName == null) {
4094            return -1;
4095        }
4096        // reader
4097        synchronized (mPackages) {
4098            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4099            if (suid == null) {
4100                return -1;
4101            }
4102            return suid.userId;
4103        }
4104    }
4105
4106    @Override
4107    public int getFlagsForUid(int uid) {
4108        synchronized (mPackages) {
4109            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4110            if (obj instanceof SharedUserSetting) {
4111                final SharedUserSetting sus = (SharedUserSetting) obj;
4112                return sus.pkgFlags;
4113            } else if (obj instanceof PackageSetting) {
4114                final PackageSetting ps = (PackageSetting) obj;
4115                return ps.pkgFlags;
4116            }
4117        }
4118        return 0;
4119    }
4120
4121    @Override
4122    public int getPrivateFlagsForUid(int uid) {
4123        synchronized (mPackages) {
4124            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4125            if (obj instanceof SharedUserSetting) {
4126                final SharedUserSetting sus = (SharedUserSetting) obj;
4127                return sus.pkgPrivateFlags;
4128            } else if (obj instanceof PackageSetting) {
4129                final PackageSetting ps = (PackageSetting) obj;
4130                return ps.pkgPrivateFlags;
4131            }
4132        }
4133        return 0;
4134    }
4135
4136    @Override
4137    public boolean isUidPrivileged(int uid) {
4138        uid = UserHandle.getAppId(uid);
4139        // reader
4140        synchronized (mPackages) {
4141            Object obj = mSettings.getUserIdLPr(uid);
4142            if (obj instanceof SharedUserSetting) {
4143                final SharedUserSetting sus = (SharedUserSetting) obj;
4144                final Iterator<PackageSetting> it = sus.packages.iterator();
4145                while (it.hasNext()) {
4146                    if (it.next().isPrivileged()) {
4147                        return true;
4148                    }
4149                }
4150            } else if (obj instanceof PackageSetting) {
4151                final PackageSetting ps = (PackageSetting) obj;
4152                return ps.isPrivileged();
4153            }
4154        }
4155        return false;
4156    }
4157
4158    @Override
4159    public String[] getAppOpPermissionPackages(String permissionName) {
4160        synchronized (mPackages) {
4161            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4162            if (pkgs == null) {
4163                return null;
4164            }
4165            return pkgs.toArray(new String[pkgs.size()]);
4166        }
4167    }
4168
4169    @Override
4170    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4171            int flags, int userId) {
4172        if (!sUserManager.exists(userId)) return null;
4173        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4174        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4175        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4176    }
4177
4178    @Override
4179    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4180            IntentFilter filter, int match, ComponentName activity) {
4181        final int userId = UserHandle.getCallingUserId();
4182        if (DEBUG_PREFERRED) {
4183            Log.v(TAG, "setLastChosenActivity intent=" + intent
4184                + " resolvedType=" + resolvedType
4185                + " flags=" + flags
4186                + " filter=" + filter
4187                + " match=" + match
4188                + " activity=" + activity);
4189            filter.dump(new PrintStreamPrinter(System.out), "    ");
4190        }
4191        intent.setComponent(null);
4192        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4193        // Find any earlier preferred or last chosen entries and nuke them
4194        findPreferredActivity(intent, resolvedType,
4195                flags, query, 0, false, true, false, userId);
4196        // Add the new activity as the last chosen for this filter
4197        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4198                "Setting last chosen");
4199    }
4200
4201    @Override
4202    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4203        final int userId = UserHandle.getCallingUserId();
4204        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4205        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4206        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4207                false, false, false, userId);
4208    }
4209
4210    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4211            int flags, List<ResolveInfo> query, int userId) {
4212        if (query != null) {
4213            final int N = query.size();
4214            if (N == 1) {
4215                return query.get(0);
4216            } else if (N > 1) {
4217                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4218                // If there is more than one activity with the same priority,
4219                // then let the user decide between them.
4220                ResolveInfo r0 = query.get(0);
4221                ResolveInfo r1 = query.get(1);
4222                if (DEBUG_INTENT_MATCHING || debug) {
4223                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4224                            + r1.activityInfo.name + "=" + r1.priority);
4225                }
4226                // If the first activity has a higher priority, or a different
4227                // default, then it is always desireable to pick it.
4228                if (r0.priority != r1.priority
4229                        || r0.preferredOrder != r1.preferredOrder
4230                        || r0.isDefault != r1.isDefault) {
4231                    return query.get(0);
4232                }
4233                // If we have saved a preference for a preferred activity for
4234                // this Intent, use that.
4235                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4236                        flags, query, r0.priority, true, false, debug, userId);
4237                if (ri != null) {
4238                    return ri;
4239                }
4240                ri = new ResolveInfo(mResolveInfo);
4241                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4242                ri.activityInfo.applicationInfo = new ApplicationInfo(
4243                        ri.activityInfo.applicationInfo);
4244                if (userId != 0) {
4245                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4246                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4247                }
4248                // Make sure that the resolver is displayable in car mode
4249                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4250                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4251                return ri;
4252            }
4253        }
4254        return null;
4255    }
4256
4257    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4258            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4259        final int N = query.size();
4260        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4261                .get(userId);
4262        // Get the list of persistent preferred activities that handle the intent
4263        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4264        List<PersistentPreferredActivity> pprefs = ppir != null
4265                ? ppir.queryIntent(intent, resolvedType,
4266                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4267                : null;
4268        if (pprefs != null && pprefs.size() > 0) {
4269            final int M = pprefs.size();
4270            for (int i=0; i<M; i++) {
4271                final PersistentPreferredActivity ppa = pprefs.get(i);
4272                if (DEBUG_PREFERRED || debug) {
4273                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4274                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4275                            + "\n  component=" + ppa.mComponent);
4276                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4277                }
4278                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4279                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4280                if (DEBUG_PREFERRED || debug) {
4281                    Slog.v(TAG, "Found persistent preferred activity:");
4282                    if (ai != null) {
4283                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4284                    } else {
4285                        Slog.v(TAG, "  null");
4286                    }
4287                }
4288                if (ai == null) {
4289                    // This previously registered persistent preferred activity
4290                    // component is no longer known. Ignore it and do NOT remove it.
4291                    continue;
4292                }
4293                for (int j=0; j<N; j++) {
4294                    final ResolveInfo ri = query.get(j);
4295                    if (!ri.activityInfo.applicationInfo.packageName
4296                            .equals(ai.applicationInfo.packageName)) {
4297                        continue;
4298                    }
4299                    if (!ri.activityInfo.name.equals(ai.name)) {
4300                        continue;
4301                    }
4302                    //  Found a persistent preference that can handle the intent.
4303                    if (DEBUG_PREFERRED || debug) {
4304                        Slog.v(TAG, "Returning persistent preferred activity: " +
4305                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4306                    }
4307                    return ri;
4308                }
4309            }
4310        }
4311        return null;
4312    }
4313
4314    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4315            List<ResolveInfo> query, int priority, boolean always,
4316            boolean removeMatches, boolean debug, int userId) {
4317        if (!sUserManager.exists(userId)) return null;
4318        // writer
4319        synchronized (mPackages) {
4320            if (intent.getSelector() != null) {
4321                intent = intent.getSelector();
4322            }
4323            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4324
4325            // Try to find a matching persistent preferred activity.
4326            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4327                    debug, userId);
4328
4329            // If a persistent preferred activity matched, use it.
4330            if (pri != null) {
4331                return pri;
4332            }
4333
4334            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4335            // Get the list of preferred activities that handle the intent
4336            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4337            List<PreferredActivity> prefs = pir != null
4338                    ? pir.queryIntent(intent, resolvedType,
4339                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4340                    : null;
4341            if (prefs != null && prefs.size() > 0) {
4342                boolean changed = false;
4343                try {
4344                    // First figure out how good the original match set is.
4345                    // We will only allow preferred activities that came
4346                    // from the same match quality.
4347                    int match = 0;
4348
4349                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4350
4351                    final int N = query.size();
4352                    for (int j=0; j<N; j++) {
4353                        final ResolveInfo ri = query.get(j);
4354                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4355                                + ": 0x" + Integer.toHexString(match));
4356                        if (ri.match > match) {
4357                            match = ri.match;
4358                        }
4359                    }
4360
4361                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4362                            + Integer.toHexString(match));
4363
4364                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4365                    final int M = prefs.size();
4366                    for (int i=0; i<M; i++) {
4367                        final PreferredActivity pa = prefs.get(i);
4368                        if (DEBUG_PREFERRED || debug) {
4369                            Slog.v(TAG, "Checking PreferredActivity ds="
4370                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4371                                    + "\n  component=" + pa.mPref.mComponent);
4372                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4373                        }
4374                        if (pa.mPref.mMatch != match) {
4375                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4376                                    + Integer.toHexString(pa.mPref.mMatch));
4377                            continue;
4378                        }
4379                        // If it's not an "always" type preferred activity and that's what we're
4380                        // looking for, skip it.
4381                        if (always && !pa.mPref.mAlways) {
4382                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4383                            continue;
4384                        }
4385                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4386                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4387                        if (DEBUG_PREFERRED || debug) {
4388                            Slog.v(TAG, "Found preferred activity:");
4389                            if (ai != null) {
4390                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4391                            } else {
4392                                Slog.v(TAG, "  null");
4393                            }
4394                        }
4395                        if (ai == null) {
4396                            // This previously registered preferred activity
4397                            // component is no longer known.  Most likely an update
4398                            // to the app was installed and in the new version this
4399                            // component no longer exists.  Clean it up by removing
4400                            // it from the preferred activities list, and skip it.
4401                            Slog.w(TAG, "Removing dangling preferred activity: "
4402                                    + pa.mPref.mComponent);
4403                            pir.removeFilter(pa);
4404                            changed = true;
4405                            continue;
4406                        }
4407                        for (int j=0; j<N; j++) {
4408                            final ResolveInfo ri = query.get(j);
4409                            if (!ri.activityInfo.applicationInfo.packageName
4410                                    .equals(ai.applicationInfo.packageName)) {
4411                                continue;
4412                            }
4413                            if (!ri.activityInfo.name.equals(ai.name)) {
4414                                continue;
4415                            }
4416
4417                            if (removeMatches) {
4418                                pir.removeFilter(pa);
4419                                changed = true;
4420                                if (DEBUG_PREFERRED) {
4421                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4422                                }
4423                                break;
4424                            }
4425
4426                            // Okay we found a previously set preferred or last chosen app.
4427                            // If the result set is different from when this
4428                            // was created, we need to clear it and re-ask the
4429                            // user their preference, if we're looking for an "always" type entry.
4430                            if (always && !pa.mPref.sameSet(query)) {
4431                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4432                                        + intent + " type " + resolvedType);
4433                                if (DEBUG_PREFERRED) {
4434                                    Slog.v(TAG, "Removing preferred activity since set changed "
4435                                            + pa.mPref.mComponent);
4436                                }
4437                                pir.removeFilter(pa);
4438                                // Re-add the filter as a "last chosen" entry (!always)
4439                                PreferredActivity lastChosen = new PreferredActivity(
4440                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4441                                pir.addFilter(lastChosen);
4442                                changed = true;
4443                                return null;
4444                            }
4445
4446                            // Yay! Either the set matched or we're looking for the last chosen
4447                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4448                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4449                            return ri;
4450                        }
4451                    }
4452                } finally {
4453                    if (changed) {
4454                        if (DEBUG_PREFERRED) {
4455                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4456                        }
4457                        scheduleWritePackageRestrictionsLocked(userId);
4458                    }
4459                }
4460            }
4461        }
4462        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4463        return null;
4464    }
4465
4466    /*
4467     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4468     */
4469    @Override
4470    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4471            int targetUserId) {
4472        mContext.enforceCallingOrSelfPermission(
4473                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4474        List<CrossProfileIntentFilter> matches =
4475                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4476        if (matches != null) {
4477            int size = matches.size();
4478            for (int i = 0; i < size; i++) {
4479                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4480            }
4481        }
4482        if (hasWebURI(intent)) {
4483            // cross-profile app linking works only towards the parent.
4484            final UserInfo parent = getProfileParent(sourceUserId);
4485            synchronized(mPackages) {
4486                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4487                        intent, resolvedType, 0, sourceUserId, parent.id);
4488                return xpDomainInfo != null;
4489            }
4490        }
4491        return false;
4492    }
4493
4494    private UserInfo getProfileParent(int userId) {
4495        final long identity = Binder.clearCallingIdentity();
4496        try {
4497            return sUserManager.getProfileParent(userId);
4498        } finally {
4499            Binder.restoreCallingIdentity(identity);
4500        }
4501    }
4502
4503    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4504            String resolvedType, int userId) {
4505        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4506        if (resolver != null) {
4507            return resolver.queryIntent(intent, resolvedType, false, userId);
4508        }
4509        return null;
4510    }
4511
4512    @Override
4513    public List<ResolveInfo> queryIntentActivities(Intent intent,
4514            String resolvedType, int flags, int userId) {
4515        if (!sUserManager.exists(userId)) return Collections.emptyList();
4516        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4517        ComponentName comp = intent.getComponent();
4518        if (comp == null) {
4519            if (intent.getSelector() != null) {
4520                intent = intent.getSelector();
4521                comp = intent.getComponent();
4522            }
4523        }
4524
4525        if (comp != null) {
4526            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4527            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4528            if (ai != null) {
4529                final ResolveInfo ri = new ResolveInfo();
4530                ri.activityInfo = ai;
4531                list.add(ri);
4532            }
4533            return list;
4534        }
4535
4536        // reader
4537        synchronized (mPackages) {
4538            final String pkgName = intent.getPackage();
4539            if (pkgName == null) {
4540                List<CrossProfileIntentFilter> matchingFilters =
4541                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4542                // Check for results that need to skip the current profile.
4543                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4544                        resolvedType, flags, userId);
4545                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4546                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4547                    result.add(xpResolveInfo);
4548                    return filterIfNotPrimaryUser(result, userId);
4549                }
4550
4551                // Check for results in the current profile.
4552                List<ResolveInfo> result = mActivities.queryIntent(
4553                        intent, resolvedType, flags, userId);
4554
4555                // Check for cross profile results.
4556                xpResolveInfo = queryCrossProfileIntents(
4557                        matchingFilters, intent, resolvedType, flags, userId);
4558                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4559                    result.add(xpResolveInfo);
4560                    Collections.sort(result, mResolvePrioritySorter);
4561                }
4562                result = filterIfNotPrimaryUser(result, userId);
4563                if (hasWebURI(intent)) {
4564                    CrossProfileDomainInfo xpDomainInfo = null;
4565                    final UserInfo parent = getProfileParent(userId);
4566                    if (parent != null) {
4567                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4568                                flags, userId, parent.id);
4569                    }
4570                    if (xpDomainInfo != null) {
4571                        if (xpResolveInfo != null) {
4572                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4573                            // in the result.
4574                            result.remove(xpResolveInfo);
4575                        }
4576                        if (result.size() == 0) {
4577                            result.add(xpDomainInfo.resolveInfo);
4578                            return result;
4579                        }
4580                    } else if (result.size() <= 1) {
4581                        return result;
4582                    }
4583                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4584                            xpDomainInfo, userId);
4585                    Collections.sort(result, mResolvePrioritySorter);
4586                }
4587                return result;
4588            }
4589            final PackageParser.Package pkg = mPackages.get(pkgName);
4590            if (pkg != null) {
4591                return filterIfNotPrimaryUser(
4592                        mActivities.queryIntentForPackage(
4593                                intent, resolvedType, flags, pkg.activities, userId),
4594                        userId);
4595            }
4596            return new ArrayList<ResolveInfo>();
4597        }
4598    }
4599
4600    private static class CrossProfileDomainInfo {
4601        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4602        ResolveInfo resolveInfo;
4603        /* Best domain verification status of the activities found in the other profile */
4604        int bestDomainVerificationStatus;
4605    }
4606
4607    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4608            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4609        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4610                sourceUserId)) {
4611            return null;
4612        }
4613        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4614                resolvedType, flags, parentUserId);
4615
4616        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4617            return null;
4618        }
4619        CrossProfileDomainInfo result = null;
4620        int size = resultTargetUser.size();
4621        for (int i = 0; i < size; i++) {
4622            ResolveInfo riTargetUser = resultTargetUser.get(i);
4623            // Intent filter verification is only for filters that specify a host. So don't return
4624            // those that handle all web uris.
4625            if (riTargetUser.handleAllWebDataURI) {
4626                continue;
4627            }
4628            String packageName = riTargetUser.activityInfo.packageName;
4629            PackageSetting ps = mSettings.mPackages.get(packageName);
4630            if (ps == null) {
4631                continue;
4632            }
4633            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4634            int status = (int)(verificationState >> 32);
4635            if (result == null) {
4636                result = new CrossProfileDomainInfo();
4637                result.resolveInfo =
4638                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4639                result.bestDomainVerificationStatus = status;
4640            } else {
4641                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4642                        result.bestDomainVerificationStatus);
4643            }
4644        }
4645        // Don't consider matches with status NEVER across profiles.
4646        if (result != null && result.bestDomainVerificationStatus
4647                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4648            return null;
4649        }
4650        return result;
4651    }
4652
4653    /**
4654     * Verification statuses are ordered from the worse to the best, except for
4655     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4656     */
4657    private int bestDomainVerificationStatus(int status1, int status2) {
4658        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4659            return status2;
4660        }
4661        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4662            return status1;
4663        }
4664        return (int) MathUtils.max(status1, status2);
4665    }
4666
4667    private boolean isUserEnabled(int userId) {
4668        long callingId = Binder.clearCallingIdentity();
4669        try {
4670            UserInfo userInfo = sUserManager.getUserInfo(userId);
4671            return userInfo != null && userInfo.isEnabled();
4672        } finally {
4673            Binder.restoreCallingIdentity(callingId);
4674        }
4675    }
4676
4677    /**
4678     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4679     *
4680     * @return filtered list
4681     */
4682    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4683        if (userId == UserHandle.USER_OWNER) {
4684            return resolveInfos;
4685        }
4686        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4687            ResolveInfo info = resolveInfos.get(i);
4688            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4689                resolveInfos.remove(i);
4690            }
4691        }
4692        return resolveInfos;
4693    }
4694
4695    private static boolean hasWebURI(Intent intent) {
4696        if (intent.getData() == null) {
4697            return false;
4698        }
4699        final String scheme = intent.getScheme();
4700        if (TextUtils.isEmpty(scheme)) {
4701            return false;
4702        }
4703        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4704    }
4705
4706    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4707            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4708            int userId) {
4709        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4710
4711        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4712            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4713                    candidates.size());
4714        }
4715
4716        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4717        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4719        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4720        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4721        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4722
4723        synchronized (mPackages) {
4724            final int count = candidates.size();
4725            // First, try to use linked apps. Partition the candidates into four lists:
4726            // one for the final results, one for the "do not use ever", one for "undefined status"
4727            // and finally one for "browser app type".
4728            for (int n=0; n<count; n++) {
4729                ResolveInfo info = candidates.get(n);
4730                String packageName = info.activityInfo.packageName;
4731                PackageSetting ps = mSettings.mPackages.get(packageName);
4732                if (ps != null) {
4733                    // Add to the special match all list (Browser use case)
4734                    if (info.handleAllWebDataURI) {
4735                        matchAllList.add(info);
4736                        continue;
4737                    }
4738                    // Try to get the status from User settings first
4739                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4740                    int status = (int)(packedStatus >> 32);
4741                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4742                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4743                        if (DEBUG_DOMAIN_VERIFICATION) {
4744                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4745                                    + " : linkgen=" + linkGeneration);
4746                        }
4747                        // Use link-enabled generation as preferredOrder, i.e.
4748                        // prefer newly-enabled over earlier-enabled.
4749                        info.preferredOrder = linkGeneration;
4750                        alwaysList.add(info);
4751                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4752                        if (DEBUG_DOMAIN_VERIFICATION) {
4753                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4754                        }
4755                        neverList.add(info);
4756                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4757                        if (DEBUG_DOMAIN_VERIFICATION) {
4758                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4759                        }
4760                        alwaysAskList.add(info);
4761                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4762                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4763                        if (DEBUG_DOMAIN_VERIFICATION) {
4764                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4765                        }
4766                        undefinedList.add(info);
4767                    }
4768                }
4769            }
4770
4771            // We'll want to include browser possibilities in a few cases
4772            boolean includeBrowser = false;
4773
4774            // First try to add the "always" resolution(s) for the current user, if any
4775            if (alwaysList.size() > 0) {
4776                result.addAll(alwaysList);
4777            // if there is an "always" for the parent user, add it.
4778            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4779                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4780                result.add(xpDomainInfo.resolveInfo);
4781            } else {
4782                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4783                result.addAll(undefinedList);
4784                if (xpDomainInfo != null && (
4785                        xpDomainInfo.bestDomainVerificationStatus
4786                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4787                        || xpDomainInfo.bestDomainVerificationStatus
4788                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4789                    result.add(xpDomainInfo.resolveInfo);
4790                }
4791                includeBrowser = true;
4792            }
4793
4794            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4795            // If there were 'always' entries their preferred order has been set, so we also
4796            // back that off to make the alternatives equivalent
4797            if (alwaysAskList.size() > 0) {
4798                for (ResolveInfo i : result) {
4799                    i.preferredOrder = 0;
4800                }
4801                result.addAll(alwaysAskList);
4802                includeBrowser = true;
4803            }
4804
4805            if (includeBrowser) {
4806                // Also add browsers (all of them or only the default one)
4807                if (DEBUG_DOMAIN_VERIFICATION) {
4808                    Slog.v(TAG, "   ...including browsers in candidate set");
4809                }
4810                if ((matchFlags & MATCH_ALL) != 0) {
4811                    result.addAll(matchAllList);
4812                } else {
4813                    // Browser/generic handling case.  If there's a default browser, go straight
4814                    // to that (but only if there is no other higher-priority match).
4815                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4816                    int maxMatchPrio = 0;
4817                    ResolveInfo defaultBrowserMatch = null;
4818                    final int numCandidates = matchAllList.size();
4819                    for (int n = 0; n < numCandidates; n++) {
4820                        ResolveInfo info = matchAllList.get(n);
4821                        // track the highest overall match priority...
4822                        if (info.priority > maxMatchPrio) {
4823                            maxMatchPrio = info.priority;
4824                        }
4825                        // ...and the highest-priority default browser match
4826                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4827                            if (defaultBrowserMatch == null
4828                                    || (defaultBrowserMatch.priority < info.priority)) {
4829                                if (debug) {
4830                                    Slog.v(TAG, "Considering default browser match " + info);
4831                                }
4832                                defaultBrowserMatch = info;
4833                            }
4834                        }
4835                    }
4836                    if (defaultBrowserMatch != null
4837                            && defaultBrowserMatch.priority >= maxMatchPrio
4838                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4839                    {
4840                        if (debug) {
4841                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4842                        }
4843                        result.add(defaultBrowserMatch);
4844                    } else {
4845                        result.addAll(matchAllList);
4846                    }
4847                }
4848
4849                // If there is nothing selected, add all candidates and remove the ones that the user
4850                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4851                if (result.size() == 0) {
4852                    result.addAll(candidates);
4853                    result.removeAll(neverList);
4854                }
4855            }
4856        }
4857        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4858            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4859                    result.size());
4860            for (ResolveInfo info : result) {
4861                Slog.v(TAG, "  + " + info.activityInfo);
4862            }
4863        }
4864        return result;
4865    }
4866
4867    // Returns a packed value as a long:
4868    //
4869    // high 'int'-sized word: link status: undefined/ask/never/always.
4870    // low 'int'-sized word: relative priority among 'always' results.
4871    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4872        long result = ps.getDomainVerificationStatusForUser(userId);
4873        // if none available, get the master status
4874        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4875            if (ps.getIntentFilterVerificationInfo() != null) {
4876                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4877            }
4878        }
4879        return result;
4880    }
4881
4882    private ResolveInfo querySkipCurrentProfileIntents(
4883            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4884            int flags, int sourceUserId) {
4885        if (matchingFilters != null) {
4886            int size = matchingFilters.size();
4887            for (int i = 0; i < size; i ++) {
4888                CrossProfileIntentFilter filter = matchingFilters.get(i);
4889                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4890                    // Checking if there are activities in the target user that can handle the
4891                    // intent.
4892                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4893                            flags, sourceUserId);
4894                    if (resolveInfo != null) {
4895                        return resolveInfo;
4896                    }
4897                }
4898            }
4899        }
4900        return null;
4901    }
4902
4903    // Return matching ResolveInfo if any for skip current profile intent filters.
4904    private ResolveInfo queryCrossProfileIntents(
4905            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4906            int flags, int sourceUserId) {
4907        if (matchingFilters != null) {
4908            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4909            // match the same intent. For performance reasons, it is better not to
4910            // run queryIntent twice for the same userId
4911            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4912            int size = matchingFilters.size();
4913            for (int i = 0; i < size; i++) {
4914                CrossProfileIntentFilter filter = matchingFilters.get(i);
4915                int targetUserId = filter.getTargetUserId();
4916                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4917                        && !alreadyTriedUserIds.get(targetUserId)) {
4918                    // Checking if there are activities in the target user that can handle the
4919                    // intent.
4920                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4921                            flags, sourceUserId);
4922                    if (resolveInfo != null) return resolveInfo;
4923                    alreadyTriedUserIds.put(targetUserId, true);
4924                }
4925            }
4926        }
4927        return null;
4928    }
4929
4930    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4931            String resolvedType, int flags, int sourceUserId) {
4932        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4933                resolvedType, flags, filter.getTargetUserId());
4934        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4935            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4936        }
4937        return null;
4938    }
4939
4940    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4941            int sourceUserId, int targetUserId) {
4942        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4943        String className;
4944        if (targetUserId == UserHandle.USER_OWNER) {
4945            className = FORWARD_INTENT_TO_USER_OWNER;
4946        } else {
4947            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4948        }
4949        ComponentName forwardingActivityComponentName = new ComponentName(
4950                mAndroidApplication.packageName, className);
4951        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4952                sourceUserId);
4953        if (targetUserId == UserHandle.USER_OWNER) {
4954            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4955            forwardingResolveInfo.noResourceId = true;
4956        }
4957        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4958        forwardingResolveInfo.priority = 0;
4959        forwardingResolveInfo.preferredOrder = 0;
4960        forwardingResolveInfo.match = 0;
4961        forwardingResolveInfo.isDefault = true;
4962        forwardingResolveInfo.filter = filter;
4963        forwardingResolveInfo.targetUserId = targetUserId;
4964        return forwardingResolveInfo;
4965    }
4966
4967    @Override
4968    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4969            Intent[] specifics, String[] specificTypes, Intent intent,
4970            String resolvedType, int flags, int userId) {
4971        if (!sUserManager.exists(userId)) return Collections.emptyList();
4972        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4973                false, "query intent activity options");
4974        final String resultsAction = intent.getAction();
4975
4976        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4977                | PackageManager.GET_RESOLVED_FILTER, userId);
4978
4979        if (DEBUG_INTENT_MATCHING) {
4980            Log.v(TAG, "Query " + intent + ": " + results);
4981        }
4982
4983        int specificsPos = 0;
4984        int N;
4985
4986        // todo: note that the algorithm used here is O(N^2).  This
4987        // isn't a problem in our current environment, but if we start running
4988        // into situations where we have more than 5 or 10 matches then this
4989        // should probably be changed to something smarter...
4990
4991        // First we go through and resolve each of the specific items
4992        // that were supplied, taking care of removing any corresponding
4993        // duplicate items in the generic resolve list.
4994        if (specifics != null) {
4995            for (int i=0; i<specifics.length; i++) {
4996                final Intent sintent = specifics[i];
4997                if (sintent == null) {
4998                    continue;
4999                }
5000
5001                if (DEBUG_INTENT_MATCHING) {
5002                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5003                }
5004
5005                String action = sintent.getAction();
5006                if (resultsAction != null && resultsAction.equals(action)) {
5007                    // If this action was explicitly requested, then don't
5008                    // remove things that have it.
5009                    action = null;
5010                }
5011
5012                ResolveInfo ri = null;
5013                ActivityInfo ai = null;
5014
5015                ComponentName comp = sintent.getComponent();
5016                if (comp == null) {
5017                    ri = resolveIntent(
5018                        sintent,
5019                        specificTypes != null ? specificTypes[i] : null,
5020                            flags, userId);
5021                    if (ri == null) {
5022                        continue;
5023                    }
5024                    if (ri == mResolveInfo) {
5025                        // ACK!  Must do something better with this.
5026                    }
5027                    ai = ri.activityInfo;
5028                    comp = new ComponentName(ai.applicationInfo.packageName,
5029                            ai.name);
5030                } else {
5031                    ai = getActivityInfo(comp, flags, userId);
5032                    if (ai == null) {
5033                        continue;
5034                    }
5035                }
5036
5037                // Look for any generic query activities that are duplicates
5038                // of this specific one, and remove them from the results.
5039                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5040                N = results.size();
5041                int j;
5042                for (j=specificsPos; j<N; j++) {
5043                    ResolveInfo sri = results.get(j);
5044                    if ((sri.activityInfo.name.equals(comp.getClassName())
5045                            && sri.activityInfo.applicationInfo.packageName.equals(
5046                                    comp.getPackageName()))
5047                        || (action != null && sri.filter.matchAction(action))) {
5048                        results.remove(j);
5049                        if (DEBUG_INTENT_MATCHING) Log.v(
5050                            TAG, "Removing duplicate item from " + j
5051                            + " due to specific " + specificsPos);
5052                        if (ri == null) {
5053                            ri = sri;
5054                        }
5055                        j--;
5056                        N--;
5057                    }
5058                }
5059
5060                // Add this specific item to its proper place.
5061                if (ri == null) {
5062                    ri = new ResolveInfo();
5063                    ri.activityInfo = ai;
5064                }
5065                results.add(specificsPos, ri);
5066                ri.specificIndex = i;
5067                specificsPos++;
5068            }
5069        }
5070
5071        // Now we go through the remaining generic results and remove any
5072        // duplicate actions that are found here.
5073        N = results.size();
5074        for (int i=specificsPos; i<N-1; i++) {
5075            final ResolveInfo rii = results.get(i);
5076            if (rii.filter == null) {
5077                continue;
5078            }
5079
5080            // Iterate over all of the actions of this result's intent
5081            // filter...  typically this should be just one.
5082            final Iterator<String> it = rii.filter.actionsIterator();
5083            if (it == null) {
5084                continue;
5085            }
5086            while (it.hasNext()) {
5087                final String action = it.next();
5088                if (resultsAction != null && resultsAction.equals(action)) {
5089                    // If this action was explicitly requested, then don't
5090                    // remove things that have it.
5091                    continue;
5092                }
5093                for (int j=i+1; j<N; j++) {
5094                    final ResolveInfo rij = results.get(j);
5095                    if (rij.filter != null && rij.filter.hasAction(action)) {
5096                        results.remove(j);
5097                        if (DEBUG_INTENT_MATCHING) Log.v(
5098                            TAG, "Removing duplicate item from " + j
5099                            + " due to action " + action + " at " + i);
5100                        j--;
5101                        N--;
5102                    }
5103                }
5104            }
5105
5106            // If the caller didn't request filter information, drop it now
5107            // so we don't have to marshall/unmarshall it.
5108            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5109                rii.filter = null;
5110            }
5111        }
5112
5113        // Filter out the caller activity if so requested.
5114        if (caller != null) {
5115            N = results.size();
5116            for (int i=0; i<N; i++) {
5117                ActivityInfo ainfo = results.get(i).activityInfo;
5118                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5119                        && caller.getClassName().equals(ainfo.name)) {
5120                    results.remove(i);
5121                    break;
5122                }
5123            }
5124        }
5125
5126        // If the caller didn't request filter information,
5127        // drop them now so we don't have to
5128        // marshall/unmarshall it.
5129        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5130            N = results.size();
5131            for (int i=0; i<N; i++) {
5132                results.get(i).filter = null;
5133            }
5134        }
5135
5136        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5137        return results;
5138    }
5139
5140    @Override
5141    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5142            int userId) {
5143        if (!sUserManager.exists(userId)) return Collections.emptyList();
5144        ComponentName comp = intent.getComponent();
5145        if (comp == null) {
5146            if (intent.getSelector() != null) {
5147                intent = intent.getSelector();
5148                comp = intent.getComponent();
5149            }
5150        }
5151        if (comp != null) {
5152            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5153            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5154            if (ai != null) {
5155                ResolveInfo ri = new ResolveInfo();
5156                ri.activityInfo = ai;
5157                list.add(ri);
5158            }
5159            return list;
5160        }
5161
5162        // reader
5163        synchronized (mPackages) {
5164            String pkgName = intent.getPackage();
5165            if (pkgName == null) {
5166                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5167            }
5168            final PackageParser.Package pkg = mPackages.get(pkgName);
5169            if (pkg != null) {
5170                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5171                        userId);
5172            }
5173            return null;
5174        }
5175    }
5176
5177    @Override
5178    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5179        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5180        if (!sUserManager.exists(userId)) return null;
5181        if (query != null) {
5182            if (query.size() >= 1) {
5183                // If there is more than one service with the same priority,
5184                // just arbitrarily pick the first one.
5185                return query.get(0);
5186            }
5187        }
5188        return null;
5189    }
5190
5191    @Override
5192    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5193            int userId) {
5194        if (!sUserManager.exists(userId)) return Collections.emptyList();
5195        ComponentName comp = intent.getComponent();
5196        if (comp == null) {
5197            if (intent.getSelector() != null) {
5198                intent = intent.getSelector();
5199                comp = intent.getComponent();
5200            }
5201        }
5202        if (comp != null) {
5203            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5204            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5205            if (si != null) {
5206                final ResolveInfo ri = new ResolveInfo();
5207                ri.serviceInfo = si;
5208                list.add(ri);
5209            }
5210            return list;
5211        }
5212
5213        // reader
5214        synchronized (mPackages) {
5215            String pkgName = intent.getPackage();
5216            if (pkgName == null) {
5217                return mServices.queryIntent(intent, resolvedType, flags, userId);
5218            }
5219            final PackageParser.Package pkg = mPackages.get(pkgName);
5220            if (pkg != null) {
5221                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5222                        userId);
5223            }
5224            return null;
5225        }
5226    }
5227
5228    @Override
5229    public List<ResolveInfo> queryIntentContentProviders(
5230            Intent intent, String resolvedType, int flags, int userId) {
5231        if (!sUserManager.exists(userId)) return Collections.emptyList();
5232        ComponentName comp = intent.getComponent();
5233        if (comp == null) {
5234            if (intent.getSelector() != null) {
5235                intent = intent.getSelector();
5236                comp = intent.getComponent();
5237            }
5238        }
5239        if (comp != null) {
5240            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5241            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5242            if (pi != null) {
5243                final ResolveInfo ri = new ResolveInfo();
5244                ri.providerInfo = pi;
5245                list.add(ri);
5246            }
5247            return list;
5248        }
5249
5250        // reader
5251        synchronized (mPackages) {
5252            String pkgName = intent.getPackage();
5253            if (pkgName == null) {
5254                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5255            }
5256            final PackageParser.Package pkg = mPackages.get(pkgName);
5257            if (pkg != null) {
5258                return mProviders.queryIntentForPackage(
5259                        intent, resolvedType, flags, pkg.providers, userId);
5260            }
5261            return null;
5262        }
5263    }
5264
5265    @Override
5266    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5267        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5268
5269        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5270
5271        // writer
5272        synchronized (mPackages) {
5273            ArrayList<PackageInfo> list;
5274            if (listUninstalled) {
5275                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5276                for (PackageSetting ps : mSettings.mPackages.values()) {
5277                    PackageInfo pi;
5278                    if (ps.pkg != null) {
5279                        pi = generatePackageInfo(ps.pkg, flags, userId);
5280                    } else {
5281                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5282                    }
5283                    if (pi != null) {
5284                        list.add(pi);
5285                    }
5286                }
5287            } else {
5288                list = new ArrayList<PackageInfo>(mPackages.size());
5289                for (PackageParser.Package p : mPackages.values()) {
5290                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5291                    if (pi != null) {
5292                        list.add(pi);
5293                    }
5294                }
5295            }
5296
5297            return new ParceledListSlice<PackageInfo>(list);
5298        }
5299    }
5300
5301    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5302            String[] permissions, boolean[] tmp, int flags, int userId) {
5303        int numMatch = 0;
5304        final PermissionsState permissionsState = ps.getPermissionsState();
5305        for (int i=0; i<permissions.length; i++) {
5306            final String permission = permissions[i];
5307            if (permissionsState.hasPermission(permission, userId)) {
5308                tmp[i] = true;
5309                numMatch++;
5310            } else {
5311                tmp[i] = false;
5312            }
5313        }
5314        if (numMatch == 0) {
5315            return;
5316        }
5317        PackageInfo pi;
5318        if (ps.pkg != null) {
5319            pi = generatePackageInfo(ps.pkg, flags, userId);
5320        } else {
5321            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5322        }
5323        // The above might return null in cases of uninstalled apps or install-state
5324        // skew across users/profiles.
5325        if (pi != null) {
5326            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5327                if (numMatch == permissions.length) {
5328                    pi.requestedPermissions = permissions;
5329                } else {
5330                    pi.requestedPermissions = new String[numMatch];
5331                    numMatch = 0;
5332                    for (int i=0; i<permissions.length; i++) {
5333                        if (tmp[i]) {
5334                            pi.requestedPermissions[numMatch] = permissions[i];
5335                            numMatch++;
5336                        }
5337                    }
5338                }
5339            }
5340            list.add(pi);
5341        }
5342    }
5343
5344    @Override
5345    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5346            String[] permissions, int flags, int userId) {
5347        if (!sUserManager.exists(userId)) return null;
5348        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5349
5350        // writer
5351        synchronized (mPackages) {
5352            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5353            boolean[] tmpBools = new boolean[permissions.length];
5354            if (listUninstalled) {
5355                for (PackageSetting ps : mSettings.mPackages.values()) {
5356                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5357                }
5358            } else {
5359                for (PackageParser.Package pkg : mPackages.values()) {
5360                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5361                    if (ps != null) {
5362                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5363                                userId);
5364                    }
5365                }
5366            }
5367
5368            return new ParceledListSlice<PackageInfo>(list);
5369        }
5370    }
5371
5372    @Override
5373    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5374        if (!sUserManager.exists(userId)) return null;
5375        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5376
5377        // writer
5378        synchronized (mPackages) {
5379            ArrayList<ApplicationInfo> list;
5380            if (listUninstalled) {
5381                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5382                for (PackageSetting ps : mSettings.mPackages.values()) {
5383                    ApplicationInfo ai;
5384                    if (ps.pkg != null) {
5385                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5386                                ps.readUserState(userId), userId);
5387                    } else {
5388                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5389                    }
5390                    if (ai != null) {
5391                        list.add(ai);
5392                    }
5393                }
5394            } else {
5395                list = new ArrayList<ApplicationInfo>(mPackages.size());
5396                for (PackageParser.Package p : mPackages.values()) {
5397                    if (p.mExtras != null) {
5398                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5399                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5400                        if (ai != null) {
5401                            list.add(ai);
5402                        }
5403                    }
5404                }
5405            }
5406
5407            return new ParceledListSlice<ApplicationInfo>(list);
5408        }
5409    }
5410
5411    public List<ApplicationInfo> getPersistentApplications(int flags) {
5412        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5413
5414        // reader
5415        synchronized (mPackages) {
5416            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5417            final int userId = UserHandle.getCallingUserId();
5418            while (i.hasNext()) {
5419                final PackageParser.Package p = i.next();
5420                if (p.applicationInfo != null
5421                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5422                        && (!mSafeMode || isSystemApp(p))) {
5423                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5424                    if (ps != null) {
5425                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5426                                ps.readUserState(userId), userId);
5427                        if (ai != null) {
5428                            finalList.add(ai);
5429                        }
5430                    }
5431                }
5432            }
5433        }
5434
5435        return finalList;
5436    }
5437
5438    @Override
5439    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5440        if (!sUserManager.exists(userId)) return null;
5441        // reader
5442        synchronized (mPackages) {
5443            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5444            PackageSetting ps = provider != null
5445                    ? mSettings.mPackages.get(provider.owner.packageName)
5446                    : null;
5447            return ps != null
5448                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5449                    && (!mSafeMode || (provider.info.applicationInfo.flags
5450                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5451                    ? PackageParser.generateProviderInfo(provider, flags,
5452                            ps.readUserState(userId), userId)
5453                    : null;
5454        }
5455    }
5456
5457    /**
5458     * @deprecated
5459     */
5460    @Deprecated
5461    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5462        // reader
5463        synchronized (mPackages) {
5464            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5465                    .entrySet().iterator();
5466            final int userId = UserHandle.getCallingUserId();
5467            while (i.hasNext()) {
5468                Map.Entry<String, PackageParser.Provider> entry = i.next();
5469                PackageParser.Provider p = entry.getValue();
5470                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5471
5472                if (ps != null && p.syncable
5473                        && (!mSafeMode || (p.info.applicationInfo.flags
5474                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5475                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5476                            ps.readUserState(userId), userId);
5477                    if (info != null) {
5478                        outNames.add(entry.getKey());
5479                        outInfo.add(info);
5480                    }
5481                }
5482            }
5483        }
5484    }
5485
5486    @Override
5487    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5488            int uid, int flags) {
5489        ArrayList<ProviderInfo> finalList = null;
5490        // reader
5491        synchronized (mPackages) {
5492            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5493            final int userId = processName != null ?
5494                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5495            while (i.hasNext()) {
5496                final PackageParser.Provider p = i.next();
5497                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5498                if (ps != null && p.info.authority != null
5499                        && (processName == null
5500                                || (p.info.processName.equals(processName)
5501                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5502                        && mSettings.isEnabledLPr(p.info, flags, userId)
5503                        && (!mSafeMode
5504                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5505                    if (finalList == null) {
5506                        finalList = new ArrayList<ProviderInfo>(3);
5507                    }
5508                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5509                            ps.readUserState(userId), userId);
5510                    if (info != null) {
5511                        finalList.add(info);
5512                    }
5513                }
5514            }
5515        }
5516
5517        if (finalList != null) {
5518            Collections.sort(finalList, mProviderInitOrderSorter);
5519            return new ParceledListSlice<ProviderInfo>(finalList);
5520        }
5521
5522        return null;
5523    }
5524
5525    @Override
5526    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5527            int flags) {
5528        // reader
5529        synchronized (mPackages) {
5530            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5531            return PackageParser.generateInstrumentationInfo(i, flags);
5532        }
5533    }
5534
5535    @Override
5536    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5537            int flags) {
5538        ArrayList<InstrumentationInfo> finalList =
5539            new ArrayList<InstrumentationInfo>();
5540
5541        // reader
5542        synchronized (mPackages) {
5543            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5544            while (i.hasNext()) {
5545                final PackageParser.Instrumentation p = i.next();
5546                if (targetPackage == null
5547                        || targetPackage.equals(p.info.targetPackage)) {
5548                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5549                            flags);
5550                    if (ii != null) {
5551                        finalList.add(ii);
5552                    }
5553                }
5554            }
5555        }
5556
5557        return finalList;
5558    }
5559
5560    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5561        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5562        if (overlays == null) {
5563            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5564            return;
5565        }
5566        for (PackageParser.Package opkg : overlays.values()) {
5567            // Not much to do if idmap fails: we already logged the error
5568            // and we certainly don't want to abort installation of pkg simply
5569            // because an overlay didn't fit properly. For these reasons,
5570            // ignore the return value of createIdmapForPackagePairLI.
5571            createIdmapForPackagePairLI(pkg, opkg);
5572        }
5573    }
5574
5575    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5576            PackageParser.Package opkg) {
5577        if (!opkg.mTrustedOverlay) {
5578            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5579                    opkg.baseCodePath + ": overlay not trusted");
5580            return false;
5581        }
5582        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5583        if (overlaySet == null) {
5584            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5585                    opkg.baseCodePath + " but target package has no known overlays");
5586            return false;
5587        }
5588        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5589        // TODO: generate idmap for split APKs
5590        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5591            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5592                    + opkg.baseCodePath);
5593            return false;
5594        }
5595        PackageParser.Package[] overlayArray =
5596            overlaySet.values().toArray(new PackageParser.Package[0]);
5597        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5598            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5599                return p1.mOverlayPriority - p2.mOverlayPriority;
5600            }
5601        };
5602        Arrays.sort(overlayArray, cmp);
5603
5604        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5605        int i = 0;
5606        for (PackageParser.Package p : overlayArray) {
5607            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5608        }
5609        return true;
5610    }
5611
5612    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5613        final File[] files = dir.listFiles();
5614        if (ArrayUtils.isEmpty(files)) {
5615            Log.d(TAG, "No files in app dir " + dir);
5616            return;
5617        }
5618
5619        if (DEBUG_PACKAGE_SCANNING) {
5620            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5621                    + " flags=0x" + Integer.toHexString(parseFlags));
5622        }
5623
5624        for (File file : files) {
5625            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5626                    && !PackageInstallerService.isStageName(file.getName());
5627            if (!isPackage) {
5628                // Ignore entries which are not packages
5629                continue;
5630            }
5631            try {
5632                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5633                        scanFlags, currentTime, null);
5634            } catch (PackageManagerException e) {
5635                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5636
5637                // Delete invalid userdata apps
5638                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5639                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5640                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5641                    if (file.isDirectory()) {
5642                        mInstaller.rmPackageDir(file.getAbsolutePath());
5643                    } else {
5644                        file.delete();
5645                    }
5646                }
5647            }
5648        }
5649    }
5650
5651    private static File getSettingsProblemFile() {
5652        File dataDir = Environment.getDataDirectory();
5653        File systemDir = new File(dataDir, "system");
5654        File fname = new File(systemDir, "uiderrors.txt");
5655        return fname;
5656    }
5657
5658    static void reportSettingsProblem(int priority, String msg) {
5659        logCriticalInfo(priority, msg);
5660    }
5661
5662    static void logCriticalInfo(int priority, String msg) {
5663        Slog.println(priority, TAG, msg);
5664        EventLogTags.writePmCriticalInfo(msg);
5665        try {
5666            File fname = getSettingsProblemFile();
5667            FileOutputStream out = new FileOutputStream(fname, true);
5668            PrintWriter pw = new FastPrintWriter(out);
5669            SimpleDateFormat formatter = new SimpleDateFormat();
5670            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5671            pw.println(dateString + ": " + msg);
5672            pw.close();
5673            FileUtils.setPermissions(
5674                    fname.toString(),
5675                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5676                    -1, -1);
5677        } catch (java.io.IOException e) {
5678        }
5679    }
5680
5681    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5682            PackageParser.Package pkg, File srcFile, int parseFlags)
5683            throws PackageManagerException {
5684        if (ps != null
5685                && ps.codePath.equals(srcFile)
5686                && ps.timeStamp == srcFile.lastModified()
5687                && !isCompatSignatureUpdateNeeded(pkg)
5688                && !isRecoverSignatureUpdateNeeded(pkg)) {
5689            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5690            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5691            ArraySet<PublicKey> signingKs;
5692            synchronized (mPackages) {
5693                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5694            }
5695            if (ps.signatures.mSignatures != null
5696                    && ps.signatures.mSignatures.length != 0
5697                    && signingKs != null) {
5698                // Optimization: reuse the existing cached certificates
5699                // if the package appears to be unchanged.
5700                pkg.mSignatures = ps.signatures.mSignatures;
5701                pkg.mSigningKeys = signingKs;
5702                return;
5703            }
5704
5705            Slog.w(TAG, "PackageSetting for " + ps.name
5706                    + " is missing signatures.  Collecting certs again to recover them.");
5707        } else {
5708            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5709        }
5710
5711        try {
5712            pp.collectCertificates(pkg, parseFlags);
5713            pp.collectManifestDigest(pkg);
5714        } catch (PackageParserException e) {
5715            throw PackageManagerException.from(e);
5716        }
5717    }
5718
5719    /*
5720     *  Scan a package and return the newly parsed package.
5721     *  Returns null in case of errors and the error code is stored in mLastScanError
5722     */
5723    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5724            long currentTime, UserHandle user) throws PackageManagerException {
5725        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5726        parseFlags |= mDefParseFlags;
5727        PackageParser pp = new PackageParser();
5728        pp.setSeparateProcesses(mSeparateProcesses);
5729        pp.setOnlyCoreApps(mOnlyCore);
5730        pp.setDisplayMetrics(mMetrics);
5731
5732        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5733            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5734        }
5735
5736        final PackageParser.Package pkg;
5737        try {
5738            pkg = pp.parsePackage(scanFile, parseFlags);
5739        } catch (PackageParserException e) {
5740            throw PackageManagerException.from(e);
5741        }
5742
5743        PackageSetting ps = null;
5744        PackageSetting updatedPkg;
5745        // reader
5746        synchronized (mPackages) {
5747            // Look to see if we already know about this package.
5748            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5749            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5750                // This package has been renamed to its original name.  Let's
5751                // use that.
5752                ps = mSettings.peekPackageLPr(oldName);
5753            }
5754            // If there was no original package, see one for the real package name.
5755            if (ps == null) {
5756                ps = mSettings.peekPackageLPr(pkg.packageName);
5757            }
5758            // Check to see if this package could be hiding/updating a system
5759            // package.  Must look for it either under the original or real
5760            // package name depending on our state.
5761            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5762            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5763        }
5764        boolean updatedPkgBetter = false;
5765        // First check if this is a system package that may involve an update
5766        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5767            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5768            // it needs to drop FLAG_PRIVILEGED.
5769            if (locationIsPrivileged(scanFile)) {
5770                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5771            } else {
5772                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5773            }
5774
5775            if (ps != null && !ps.codePath.equals(scanFile)) {
5776                // The path has changed from what was last scanned...  check the
5777                // version of the new path against what we have stored to determine
5778                // what to do.
5779                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5780                if (pkg.mVersionCode <= ps.versionCode) {
5781                    // The system package has been updated and the code path does not match
5782                    // Ignore entry. Skip it.
5783                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5784                            + " ignored: updated version " + ps.versionCode
5785                            + " better than this " + pkg.mVersionCode);
5786                    if (!updatedPkg.codePath.equals(scanFile)) {
5787                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5788                                + ps.name + " changing from " + updatedPkg.codePathString
5789                                + " to " + scanFile);
5790                        updatedPkg.codePath = scanFile;
5791                        updatedPkg.codePathString = scanFile.toString();
5792                        updatedPkg.resourcePath = scanFile;
5793                        updatedPkg.resourcePathString = scanFile.toString();
5794                    }
5795                    updatedPkg.pkg = pkg;
5796                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5797                            "Package " + ps.name + " at " + scanFile
5798                                    + " ignored: updated version " + ps.versionCode
5799                                    + " better than this " + pkg.mVersionCode);
5800                } else {
5801                    // The current app on the system partition is better than
5802                    // what we have updated to on the data partition; switch
5803                    // back to the system partition version.
5804                    // At this point, its safely assumed that package installation for
5805                    // apps in system partition will go through. If not there won't be a working
5806                    // version of the app
5807                    // writer
5808                    synchronized (mPackages) {
5809                        // Just remove the loaded entries from package lists.
5810                        mPackages.remove(ps.name);
5811                    }
5812
5813                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5814                            + " reverting from " + ps.codePathString
5815                            + ": new version " + pkg.mVersionCode
5816                            + " better than installed " + ps.versionCode);
5817
5818                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5819                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5820                    synchronized (mInstallLock) {
5821                        args.cleanUpResourcesLI();
5822                    }
5823                    synchronized (mPackages) {
5824                        mSettings.enableSystemPackageLPw(ps.name);
5825                    }
5826                    updatedPkgBetter = true;
5827                }
5828            }
5829        }
5830
5831        if (updatedPkg != null) {
5832            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5833            // initially
5834            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5835
5836            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5837            // flag set initially
5838            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5839                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5840            }
5841        }
5842
5843        // Verify certificates against what was last scanned
5844        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5845
5846        /*
5847         * A new system app appeared, but we already had a non-system one of the
5848         * same name installed earlier.
5849         */
5850        boolean shouldHideSystemApp = false;
5851        if (updatedPkg == null && ps != null
5852                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5853            /*
5854             * Check to make sure the signatures match first. If they don't,
5855             * wipe the installed application and its data.
5856             */
5857            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5858                    != PackageManager.SIGNATURE_MATCH) {
5859                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5860                        + " signatures don't match existing userdata copy; removing");
5861                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5862                ps = null;
5863            } else {
5864                /*
5865                 * If the newly-added system app is an older version than the
5866                 * already installed version, hide it. It will be scanned later
5867                 * and re-added like an update.
5868                 */
5869                if (pkg.mVersionCode <= ps.versionCode) {
5870                    shouldHideSystemApp = true;
5871                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5872                            + " but new version " + pkg.mVersionCode + " better than installed "
5873                            + ps.versionCode + "; hiding system");
5874                } else {
5875                    /*
5876                     * The newly found system app is a newer version that the
5877                     * one previously installed. Simply remove the
5878                     * already-installed application and replace it with our own
5879                     * while keeping the application data.
5880                     */
5881                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5882                            + " reverting from " + ps.codePathString + ": new version "
5883                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5884                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5885                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5886                    synchronized (mInstallLock) {
5887                        args.cleanUpResourcesLI();
5888                    }
5889                }
5890            }
5891        }
5892
5893        // The apk is forward locked (not public) if its code and resources
5894        // are kept in different files. (except for app in either system or
5895        // vendor path).
5896        // TODO grab this value from PackageSettings
5897        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5898            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5899                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5900            }
5901        }
5902
5903        // TODO: extend to support forward-locked splits
5904        String resourcePath = null;
5905        String baseResourcePath = null;
5906        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5907            if (ps != null && ps.resourcePathString != null) {
5908                resourcePath = ps.resourcePathString;
5909                baseResourcePath = ps.resourcePathString;
5910            } else {
5911                // Should not happen at all. Just log an error.
5912                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5913            }
5914        } else {
5915            resourcePath = pkg.codePath;
5916            baseResourcePath = pkg.baseCodePath;
5917        }
5918
5919        // Set application objects path explicitly.
5920        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5921        pkg.applicationInfo.setCodePath(pkg.codePath);
5922        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5923        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5924        pkg.applicationInfo.setResourcePath(resourcePath);
5925        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5926        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5927
5928        // Note that we invoke the following method only if we are about to unpack an application
5929        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5930                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5931
5932        /*
5933         * If the system app should be overridden by a previously installed
5934         * data, hide the system app now and let the /data/app scan pick it up
5935         * again.
5936         */
5937        if (shouldHideSystemApp) {
5938            synchronized (mPackages) {
5939                mSettings.disableSystemPackageLPw(pkg.packageName);
5940            }
5941        }
5942
5943        return scannedPkg;
5944    }
5945
5946    private static String fixProcessName(String defProcessName,
5947            String processName, int uid) {
5948        if (processName == null) {
5949            return defProcessName;
5950        }
5951        return processName;
5952    }
5953
5954    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5955            throws PackageManagerException {
5956        if (pkgSetting.signatures.mSignatures != null) {
5957            // Already existing package. Make sure signatures match
5958            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5959                    == PackageManager.SIGNATURE_MATCH;
5960            if (!match) {
5961                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5962                        == PackageManager.SIGNATURE_MATCH;
5963            }
5964            if (!match) {
5965                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5966                        == PackageManager.SIGNATURE_MATCH;
5967            }
5968            if (!match) {
5969                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5970                        + pkg.packageName + " signatures do not match the "
5971                        + "previously installed version; ignoring!");
5972            }
5973        }
5974
5975        // Check for shared user signatures
5976        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5977            // Already existing package. Make sure signatures match
5978            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5979                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5980            if (!match) {
5981                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5982                        == PackageManager.SIGNATURE_MATCH;
5983            }
5984            if (!match) {
5985                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5986                        == PackageManager.SIGNATURE_MATCH;
5987            }
5988            if (!match) {
5989                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5990                        "Package " + pkg.packageName
5991                        + " has no signatures that match those in shared user "
5992                        + pkgSetting.sharedUser.name + "; ignoring!");
5993            }
5994        }
5995    }
5996
5997    /**
5998     * Enforces that only the system UID or root's UID can call a method exposed
5999     * via Binder.
6000     *
6001     * @param message used as message if SecurityException is thrown
6002     * @throws SecurityException if the caller is not system or root
6003     */
6004    private static final void enforceSystemOrRoot(String message) {
6005        final int uid = Binder.getCallingUid();
6006        if (uid != Process.SYSTEM_UID && uid != 0) {
6007            throw new SecurityException(message);
6008        }
6009    }
6010
6011    @Override
6012    public void performBootDexOpt() {
6013        enforceSystemOrRoot("Only the system can request dexopt be performed");
6014
6015        // Before everything else, see whether we need to fstrim.
6016        try {
6017            IMountService ms = PackageHelper.getMountService();
6018            if (ms != null) {
6019                final boolean isUpgrade = isUpgrade();
6020                boolean doTrim = isUpgrade;
6021                if (doTrim) {
6022                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6023                } else {
6024                    final long interval = android.provider.Settings.Global.getLong(
6025                            mContext.getContentResolver(),
6026                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6027                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6028                    if (interval > 0) {
6029                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6030                        if (timeSinceLast > interval) {
6031                            doTrim = true;
6032                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6033                                    + "; running immediately");
6034                        }
6035                    }
6036                }
6037                if (doTrim) {
6038                    if (!isFirstBoot()) {
6039                        try {
6040                            ActivityManagerNative.getDefault().showBootMessage(
6041                                    mContext.getResources().getString(
6042                                            R.string.android_upgrading_fstrim), true);
6043                        } catch (RemoteException e) {
6044                        }
6045                    }
6046                    ms.runMaintenance();
6047                }
6048            } else {
6049                Slog.e(TAG, "Mount service unavailable!");
6050            }
6051        } catch (RemoteException e) {
6052            // Can't happen; MountService is local
6053        }
6054
6055        final ArraySet<PackageParser.Package> pkgs;
6056        synchronized (mPackages) {
6057            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6058        }
6059
6060        if (pkgs != null) {
6061            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6062            // in case the device runs out of space.
6063            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6064            // Give priority to core apps.
6065            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6066                PackageParser.Package pkg = it.next();
6067                if (pkg.coreApp) {
6068                    if (DEBUG_DEXOPT) {
6069                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6070                    }
6071                    sortedPkgs.add(pkg);
6072                    it.remove();
6073                }
6074            }
6075            // Give priority to system apps that listen for pre boot complete.
6076            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6077            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6078            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6079                PackageParser.Package pkg = it.next();
6080                if (pkgNames.contains(pkg.packageName)) {
6081                    if (DEBUG_DEXOPT) {
6082                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6083                    }
6084                    sortedPkgs.add(pkg);
6085                    it.remove();
6086                }
6087            }
6088            // Give priority to system apps.
6089            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6090                PackageParser.Package pkg = it.next();
6091                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6092                    if (DEBUG_DEXOPT) {
6093                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6094                    }
6095                    sortedPkgs.add(pkg);
6096                    it.remove();
6097                }
6098            }
6099            // Give priority to updated system apps.
6100            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6101                PackageParser.Package pkg = it.next();
6102                if (pkg.isUpdatedSystemApp()) {
6103                    if (DEBUG_DEXOPT) {
6104                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6105                    }
6106                    sortedPkgs.add(pkg);
6107                    it.remove();
6108                }
6109            }
6110            // Give priority to apps that listen for boot complete.
6111            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6112            pkgNames = getPackageNamesForIntent(intent);
6113            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6114                PackageParser.Package pkg = it.next();
6115                if (pkgNames.contains(pkg.packageName)) {
6116                    if (DEBUG_DEXOPT) {
6117                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6118                    }
6119                    sortedPkgs.add(pkg);
6120                    it.remove();
6121                }
6122            }
6123            // Filter out packages that aren't recently used.
6124            filterRecentlyUsedApps(pkgs);
6125            // Add all remaining apps.
6126            for (PackageParser.Package pkg : pkgs) {
6127                if (DEBUG_DEXOPT) {
6128                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6129                }
6130                sortedPkgs.add(pkg);
6131            }
6132
6133            // If we want to be lazy, filter everything that wasn't recently used.
6134            if (mLazyDexOpt) {
6135                filterRecentlyUsedApps(sortedPkgs);
6136            }
6137
6138            int i = 0;
6139            int total = sortedPkgs.size();
6140            File dataDir = Environment.getDataDirectory();
6141            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6142            if (lowThreshold == 0) {
6143                throw new IllegalStateException("Invalid low memory threshold");
6144            }
6145            for (PackageParser.Package pkg : sortedPkgs) {
6146                long usableSpace = dataDir.getUsableSpace();
6147                if (usableSpace < lowThreshold) {
6148                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6149                    break;
6150                }
6151                performBootDexOpt(pkg, ++i, total);
6152            }
6153        }
6154    }
6155
6156    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6157        // Filter out packages that aren't recently used.
6158        //
6159        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6160        // should do a full dexopt.
6161        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6162            int total = pkgs.size();
6163            int skipped = 0;
6164            long now = System.currentTimeMillis();
6165            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6166                PackageParser.Package pkg = i.next();
6167                long then = pkg.mLastPackageUsageTimeInMills;
6168                if (then + mDexOptLRUThresholdInMills < now) {
6169                    if (DEBUG_DEXOPT) {
6170                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6171                              ((then == 0) ? "never" : new Date(then)));
6172                    }
6173                    i.remove();
6174                    skipped++;
6175                }
6176            }
6177            if (DEBUG_DEXOPT) {
6178                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6179            }
6180        }
6181    }
6182
6183    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6184        List<ResolveInfo> ris = null;
6185        try {
6186            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6187                    intent, null, 0, UserHandle.USER_OWNER);
6188        } catch (RemoteException e) {
6189        }
6190        ArraySet<String> pkgNames = new ArraySet<String>();
6191        if (ris != null) {
6192            for (ResolveInfo ri : ris) {
6193                pkgNames.add(ri.activityInfo.packageName);
6194            }
6195        }
6196        return pkgNames;
6197    }
6198
6199    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6200        if (DEBUG_DEXOPT) {
6201            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6202        }
6203        if (!isFirstBoot()) {
6204            try {
6205                ActivityManagerNative.getDefault().showBootMessage(
6206                        mContext.getResources().getString(R.string.android_upgrading_apk,
6207                                curr, total), true);
6208            } catch (RemoteException e) {
6209            }
6210        }
6211        PackageParser.Package p = pkg;
6212        synchronized (mInstallLock) {
6213            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6214                    false /* force dex */, false /* defer */, true /* include dependencies */,
6215                    false /* boot complete */);
6216        }
6217    }
6218
6219    @Override
6220    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6221        return performDexOpt(packageName, instructionSet, false);
6222    }
6223
6224    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6225        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6226        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6227        if (!dexopt && !updateUsage) {
6228            // We aren't going to dexopt or update usage, so bail early.
6229            return false;
6230        }
6231        PackageParser.Package p;
6232        final String targetInstructionSet;
6233        synchronized (mPackages) {
6234            p = mPackages.get(packageName);
6235            if (p == null) {
6236                return false;
6237            }
6238            if (updateUsage) {
6239                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6240            }
6241            mPackageUsage.write(false);
6242            if (!dexopt) {
6243                // We aren't going to dexopt, so bail early.
6244                return false;
6245            }
6246
6247            targetInstructionSet = instructionSet != null ? instructionSet :
6248                    getPrimaryInstructionSet(p.applicationInfo);
6249            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6250                return false;
6251            }
6252        }
6253        long callingId = Binder.clearCallingIdentity();
6254        try {
6255            synchronized (mInstallLock) {
6256                final String[] instructionSets = new String[] { targetInstructionSet };
6257                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6258                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6259                        true /* boot complete */);
6260                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6261            }
6262        } finally {
6263            Binder.restoreCallingIdentity(callingId);
6264        }
6265    }
6266
6267    public ArraySet<String> getPackagesThatNeedDexOpt() {
6268        ArraySet<String> pkgs = null;
6269        synchronized (mPackages) {
6270            for (PackageParser.Package p : mPackages.values()) {
6271                if (DEBUG_DEXOPT) {
6272                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6273                }
6274                if (!p.mDexOptPerformed.isEmpty()) {
6275                    continue;
6276                }
6277                if (pkgs == null) {
6278                    pkgs = new ArraySet<String>();
6279                }
6280                pkgs.add(p.packageName);
6281            }
6282        }
6283        return pkgs;
6284    }
6285
6286    public void shutdown() {
6287        mPackageUsage.write(true);
6288    }
6289
6290    @Override
6291    public void forceDexOpt(String packageName) {
6292        enforceSystemOrRoot("forceDexOpt");
6293
6294        PackageParser.Package pkg;
6295        synchronized (mPackages) {
6296            pkg = mPackages.get(packageName);
6297            if (pkg == null) {
6298                throw new IllegalArgumentException("Missing package: " + packageName);
6299            }
6300        }
6301
6302        synchronized (mInstallLock) {
6303            final String[] instructionSets = new String[] {
6304                    getPrimaryInstructionSet(pkg.applicationInfo) };
6305            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6306                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6307                    true /* boot complete */);
6308            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6309                throw new IllegalStateException("Failed to dexopt: " + res);
6310            }
6311        }
6312    }
6313
6314    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6315        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6316            Slog.w(TAG, "Unable to update from " + oldPkg.name
6317                    + " to " + newPkg.packageName
6318                    + ": old package not in system partition");
6319            return false;
6320        } else if (mPackages.get(oldPkg.name) != null) {
6321            Slog.w(TAG, "Unable to update from " + oldPkg.name
6322                    + " to " + newPkg.packageName
6323                    + ": old package still exists");
6324            return false;
6325        }
6326        return true;
6327    }
6328
6329    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6330        int[] users = sUserManager.getUserIds();
6331        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6332        if (res < 0) {
6333            return res;
6334        }
6335        for (int user : users) {
6336            if (user != 0) {
6337                res = mInstaller.createUserData(volumeUuid, packageName,
6338                        UserHandle.getUid(user, uid), user, seinfo);
6339                if (res < 0) {
6340                    return res;
6341                }
6342            }
6343        }
6344        return res;
6345    }
6346
6347    private int removeDataDirsLI(String volumeUuid, String packageName) {
6348        int[] users = sUserManager.getUserIds();
6349        int res = 0;
6350        for (int user : users) {
6351            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6352            if (resInner < 0) {
6353                res = resInner;
6354            }
6355        }
6356
6357        return res;
6358    }
6359
6360    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6361        int[] users = sUserManager.getUserIds();
6362        int res = 0;
6363        for (int user : users) {
6364            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6365            if (resInner < 0) {
6366                res = resInner;
6367            }
6368        }
6369        return res;
6370    }
6371
6372    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6373            PackageParser.Package changingLib) {
6374        if (file.path != null) {
6375            usesLibraryFiles.add(file.path);
6376            return;
6377        }
6378        PackageParser.Package p = mPackages.get(file.apk);
6379        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6380            // If we are doing this while in the middle of updating a library apk,
6381            // then we need to make sure to use that new apk for determining the
6382            // dependencies here.  (We haven't yet finished committing the new apk
6383            // to the package manager state.)
6384            if (p == null || p.packageName.equals(changingLib.packageName)) {
6385                p = changingLib;
6386            }
6387        }
6388        if (p != null) {
6389            usesLibraryFiles.addAll(p.getAllCodePaths());
6390        }
6391    }
6392
6393    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6394            PackageParser.Package changingLib) throws PackageManagerException {
6395        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6396            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6397            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6398            for (int i=0; i<N; i++) {
6399                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6400                if (file == null) {
6401                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6402                            "Package " + pkg.packageName + " requires unavailable shared library "
6403                            + pkg.usesLibraries.get(i) + "; failing!");
6404                }
6405                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6406            }
6407            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6408            for (int i=0; i<N; i++) {
6409                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6410                if (file == null) {
6411                    Slog.w(TAG, "Package " + pkg.packageName
6412                            + " desires unavailable shared library "
6413                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6414                } else {
6415                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6416                }
6417            }
6418            N = usesLibraryFiles.size();
6419            if (N > 0) {
6420                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6421            } else {
6422                pkg.usesLibraryFiles = null;
6423            }
6424        }
6425    }
6426
6427    private static boolean hasString(List<String> list, List<String> which) {
6428        if (list == null) {
6429            return false;
6430        }
6431        for (int i=list.size()-1; i>=0; i--) {
6432            for (int j=which.size()-1; j>=0; j--) {
6433                if (which.get(j).equals(list.get(i))) {
6434                    return true;
6435                }
6436            }
6437        }
6438        return false;
6439    }
6440
6441    private void updateAllSharedLibrariesLPw() {
6442        for (PackageParser.Package pkg : mPackages.values()) {
6443            try {
6444                updateSharedLibrariesLPw(pkg, null);
6445            } catch (PackageManagerException e) {
6446                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6447            }
6448        }
6449    }
6450
6451    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6452            PackageParser.Package changingPkg) {
6453        ArrayList<PackageParser.Package> res = null;
6454        for (PackageParser.Package pkg : mPackages.values()) {
6455            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6456                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6457                if (res == null) {
6458                    res = new ArrayList<PackageParser.Package>();
6459                }
6460                res.add(pkg);
6461                try {
6462                    updateSharedLibrariesLPw(pkg, changingPkg);
6463                } catch (PackageManagerException e) {
6464                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6465                }
6466            }
6467        }
6468        return res;
6469    }
6470
6471    /**
6472     * Derive the value of the {@code cpuAbiOverride} based on the provided
6473     * value and an optional stored value from the package settings.
6474     */
6475    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6476        String cpuAbiOverride = null;
6477
6478        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6479            cpuAbiOverride = null;
6480        } else if (abiOverride != null) {
6481            cpuAbiOverride = abiOverride;
6482        } else if (settings != null) {
6483            cpuAbiOverride = settings.cpuAbiOverrideString;
6484        }
6485
6486        return cpuAbiOverride;
6487    }
6488
6489    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6490            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6491        boolean success = false;
6492        try {
6493            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6494                    currentTime, user);
6495            success = true;
6496            return res;
6497        } finally {
6498            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6499                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6500            }
6501        }
6502    }
6503
6504    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6505            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6506        final File scanFile = new File(pkg.codePath);
6507        if (pkg.applicationInfo.getCodePath() == null ||
6508                pkg.applicationInfo.getResourcePath() == null) {
6509            // Bail out. The resource and code paths haven't been set.
6510            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6511                    "Code and resource paths haven't been set correctly");
6512        }
6513
6514        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6515            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6516        } else {
6517            // Only allow system apps to be flagged as core apps.
6518            pkg.coreApp = false;
6519        }
6520
6521        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6522            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6523        }
6524
6525        if (mCustomResolverComponentName != null &&
6526                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6527            setUpCustomResolverActivity(pkg);
6528        }
6529
6530        if (pkg.packageName.equals("android")) {
6531            synchronized (mPackages) {
6532                if (mAndroidApplication != null) {
6533                    Slog.w(TAG, "*************************************************");
6534                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6535                    Slog.w(TAG, " file=" + scanFile);
6536                    Slog.w(TAG, "*************************************************");
6537                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6538                            "Core android package being redefined.  Skipping.");
6539                }
6540
6541                // Set up information for our fall-back user intent resolution activity.
6542                mPlatformPackage = pkg;
6543                pkg.mVersionCode = mSdkVersion;
6544                mAndroidApplication = pkg.applicationInfo;
6545
6546                if (!mResolverReplaced) {
6547                    mResolveActivity.applicationInfo = mAndroidApplication;
6548                    mResolveActivity.name = ResolverActivity.class.getName();
6549                    mResolveActivity.packageName = mAndroidApplication.packageName;
6550                    mResolveActivity.processName = "system:ui";
6551                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6552                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6553                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6554                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6555                    mResolveActivity.exported = true;
6556                    mResolveActivity.enabled = true;
6557                    mResolveInfo.activityInfo = mResolveActivity;
6558                    mResolveInfo.priority = 0;
6559                    mResolveInfo.preferredOrder = 0;
6560                    mResolveInfo.match = 0;
6561                    mResolveComponentName = new ComponentName(
6562                            mAndroidApplication.packageName, mResolveActivity.name);
6563                }
6564            }
6565        }
6566
6567        if (DEBUG_PACKAGE_SCANNING) {
6568            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6569                Log.d(TAG, "Scanning package " + pkg.packageName);
6570        }
6571
6572        if (mPackages.containsKey(pkg.packageName)
6573                || mSharedLibraries.containsKey(pkg.packageName)) {
6574            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6575                    "Application package " + pkg.packageName
6576                    + " already installed.  Skipping duplicate.");
6577        }
6578
6579        // If we're only installing presumed-existing packages, require that the
6580        // scanned APK is both already known and at the path previously established
6581        // for it.  Previously unknown packages we pick up normally, but if we have an
6582        // a priori expectation about this package's install presence, enforce it.
6583        // With a singular exception for new system packages. When an OTA contains
6584        // a new system package, we allow the codepath to change from a system location
6585        // to the user-installed location. If we don't allow this change, any newer,
6586        // user-installed version of the application will be ignored.
6587        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6588            if (mExpectingBetter.containsKey(pkg.packageName)) {
6589                logCriticalInfo(Log.WARN,
6590                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6591            } else {
6592                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6593                if (known != null) {
6594                    if (DEBUG_PACKAGE_SCANNING) {
6595                        Log.d(TAG, "Examining " + pkg.codePath
6596                                + " and requiring known paths " + known.codePathString
6597                                + " & " + known.resourcePathString);
6598                    }
6599                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6600                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6601                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6602                                "Application package " + pkg.packageName
6603                                + " found at " + pkg.applicationInfo.getCodePath()
6604                                + " but expected at " + known.codePathString + "; ignoring.");
6605                    }
6606                }
6607            }
6608        }
6609
6610        // Initialize package source and resource directories
6611        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6612        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6613
6614        SharedUserSetting suid = null;
6615        PackageSetting pkgSetting = null;
6616
6617        if (!isSystemApp(pkg)) {
6618            // Only system apps can use these features.
6619            pkg.mOriginalPackages = null;
6620            pkg.mRealPackage = null;
6621            pkg.mAdoptPermissions = null;
6622        }
6623
6624        // writer
6625        synchronized (mPackages) {
6626            if (pkg.mSharedUserId != null) {
6627                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6628                if (suid == null) {
6629                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6630                            "Creating application package " + pkg.packageName
6631                            + " for shared user failed");
6632                }
6633                if (DEBUG_PACKAGE_SCANNING) {
6634                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6635                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6636                                + "): packages=" + suid.packages);
6637                }
6638            }
6639
6640            // Check if we are renaming from an original package name.
6641            PackageSetting origPackage = null;
6642            String realName = null;
6643            if (pkg.mOriginalPackages != null) {
6644                // This package may need to be renamed to a previously
6645                // installed name.  Let's check on that...
6646                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6647                if (pkg.mOriginalPackages.contains(renamed)) {
6648                    // This package had originally been installed as the
6649                    // original name, and we have already taken care of
6650                    // transitioning to the new one.  Just update the new
6651                    // one to continue using the old name.
6652                    realName = pkg.mRealPackage;
6653                    if (!pkg.packageName.equals(renamed)) {
6654                        // Callers into this function may have already taken
6655                        // care of renaming the package; only do it here if
6656                        // it is not already done.
6657                        pkg.setPackageName(renamed);
6658                    }
6659
6660                } else {
6661                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6662                        if ((origPackage = mSettings.peekPackageLPr(
6663                                pkg.mOriginalPackages.get(i))) != null) {
6664                            // We do have the package already installed under its
6665                            // original name...  should we use it?
6666                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6667                                // New package is not compatible with original.
6668                                origPackage = null;
6669                                continue;
6670                            } else if (origPackage.sharedUser != null) {
6671                                // Make sure uid is compatible between packages.
6672                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6673                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6674                                            + " to " + pkg.packageName + ": old uid "
6675                                            + origPackage.sharedUser.name
6676                                            + " differs from " + pkg.mSharedUserId);
6677                                    origPackage = null;
6678                                    continue;
6679                                }
6680                            } else {
6681                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6682                                        + pkg.packageName + " to old name " + origPackage.name);
6683                            }
6684                            break;
6685                        }
6686                    }
6687                }
6688            }
6689
6690            if (mTransferedPackages.contains(pkg.packageName)) {
6691                Slog.w(TAG, "Package " + pkg.packageName
6692                        + " was transferred to another, but its .apk remains");
6693            }
6694
6695            // Just create the setting, don't add it yet. For already existing packages
6696            // the PkgSetting exists already and doesn't have to be created.
6697            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6698                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6699                    pkg.applicationInfo.primaryCpuAbi,
6700                    pkg.applicationInfo.secondaryCpuAbi,
6701                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6702                    user, false);
6703            if (pkgSetting == null) {
6704                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6705                        "Creating application package " + pkg.packageName + " failed");
6706            }
6707
6708            if (pkgSetting.origPackage != null) {
6709                // If we are first transitioning from an original package,
6710                // fix up the new package's name now.  We need to do this after
6711                // looking up the package under its new name, so getPackageLP
6712                // can take care of fiddling things correctly.
6713                pkg.setPackageName(origPackage.name);
6714
6715                // File a report about this.
6716                String msg = "New package " + pkgSetting.realName
6717                        + " renamed to replace old package " + pkgSetting.name;
6718                reportSettingsProblem(Log.WARN, msg);
6719
6720                // Make a note of it.
6721                mTransferedPackages.add(origPackage.name);
6722
6723                // No longer need to retain this.
6724                pkgSetting.origPackage = null;
6725            }
6726
6727            if (realName != null) {
6728                // Make a note of it.
6729                mTransferedPackages.add(pkg.packageName);
6730            }
6731
6732            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6733                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6734            }
6735
6736            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6737                // Check all shared libraries and map to their actual file path.
6738                // We only do this here for apps not on a system dir, because those
6739                // are the only ones that can fail an install due to this.  We
6740                // will take care of the system apps by updating all of their
6741                // library paths after the scan is done.
6742                updateSharedLibrariesLPw(pkg, null);
6743            }
6744
6745            if (mFoundPolicyFile) {
6746                SELinuxMMAC.assignSeinfoValue(pkg);
6747            }
6748
6749            pkg.applicationInfo.uid = pkgSetting.appId;
6750            pkg.mExtras = pkgSetting;
6751            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6752                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6753                    // We just determined the app is signed correctly, so bring
6754                    // over the latest parsed certs.
6755                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6756                } else {
6757                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6758                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6759                                "Package " + pkg.packageName + " upgrade keys do not match the "
6760                                + "previously installed version");
6761                    } else {
6762                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6763                        String msg = "System package " + pkg.packageName
6764                            + " signature changed; retaining data.";
6765                        reportSettingsProblem(Log.WARN, msg);
6766                    }
6767                }
6768            } else {
6769                try {
6770                    verifySignaturesLP(pkgSetting, pkg);
6771                    // We just determined the app is signed correctly, so bring
6772                    // over the latest parsed certs.
6773                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6774                } catch (PackageManagerException e) {
6775                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6776                        throw e;
6777                    }
6778                    // The signature has changed, but this package is in the system
6779                    // image...  let's recover!
6780                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6781                    // However...  if this package is part of a shared user, but it
6782                    // doesn't match the signature of the shared user, let's fail.
6783                    // What this means is that you can't change the signatures
6784                    // associated with an overall shared user, which doesn't seem all
6785                    // that unreasonable.
6786                    if (pkgSetting.sharedUser != null) {
6787                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6788                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6789                            throw new PackageManagerException(
6790                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6791                                            "Signature mismatch for shared user : "
6792                                            + pkgSetting.sharedUser);
6793                        }
6794                    }
6795                    // File a report about this.
6796                    String msg = "System package " + pkg.packageName
6797                        + " signature changed; retaining data.";
6798                    reportSettingsProblem(Log.WARN, msg);
6799                }
6800            }
6801            // Verify that this new package doesn't have any content providers
6802            // that conflict with existing packages.  Only do this if the
6803            // package isn't already installed, since we don't want to break
6804            // things that are installed.
6805            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6806                final int N = pkg.providers.size();
6807                int i;
6808                for (i=0; i<N; i++) {
6809                    PackageParser.Provider p = pkg.providers.get(i);
6810                    if (p.info.authority != null) {
6811                        String names[] = p.info.authority.split(";");
6812                        for (int j = 0; j < names.length; j++) {
6813                            if (mProvidersByAuthority.containsKey(names[j])) {
6814                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6815                                final String otherPackageName =
6816                                        ((other != null && other.getComponentName() != null) ?
6817                                                other.getComponentName().getPackageName() : "?");
6818                                throw new PackageManagerException(
6819                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6820                                                "Can't install because provider name " + names[j]
6821                                                + " (in package " + pkg.applicationInfo.packageName
6822                                                + ") is already used by " + otherPackageName);
6823                            }
6824                        }
6825                    }
6826                }
6827            }
6828
6829            if (pkg.mAdoptPermissions != null) {
6830                // This package wants to adopt ownership of permissions from
6831                // another package.
6832                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6833                    final String origName = pkg.mAdoptPermissions.get(i);
6834                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6835                    if (orig != null) {
6836                        if (verifyPackageUpdateLPr(orig, pkg)) {
6837                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6838                                    + pkg.packageName);
6839                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6840                        }
6841                    }
6842                }
6843            }
6844        }
6845
6846        final String pkgName = pkg.packageName;
6847
6848        final long scanFileTime = scanFile.lastModified();
6849        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6850        pkg.applicationInfo.processName = fixProcessName(
6851                pkg.applicationInfo.packageName,
6852                pkg.applicationInfo.processName,
6853                pkg.applicationInfo.uid);
6854
6855        File dataPath;
6856        if (mPlatformPackage == pkg) {
6857            // The system package is special.
6858            dataPath = new File(Environment.getDataDirectory(), "system");
6859
6860            pkg.applicationInfo.dataDir = dataPath.getPath();
6861
6862        } else {
6863            // This is a normal package, need to make its data directory.
6864            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6865                    UserHandle.USER_OWNER, pkg.packageName);
6866
6867            boolean uidError = false;
6868            if (dataPath.exists()) {
6869                int currentUid = 0;
6870                try {
6871                    StructStat stat = Os.stat(dataPath.getPath());
6872                    currentUid = stat.st_uid;
6873                } catch (ErrnoException e) {
6874                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6875                }
6876
6877                // If we have mismatched owners for the data path, we have a problem.
6878                if (currentUid != pkg.applicationInfo.uid) {
6879                    boolean recovered = false;
6880                    if (currentUid == 0) {
6881                        // The directory somehow became owned by root.  Wow.
6882                        // This is probably because the system was stopped while
6883                        // installd was in the middle of messing with its libs
6884                        // directory.  Ask installd to fix that.
6885                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6886                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6887                        if (ret >= 0) {
6888                            recovered = true;
6889                            String msg = "Package " + pkg.packageName
6890                                    + " unexpectedly changed to uid 0; recovered to " +
6891                                    + pkg.applicationInfo.uid;
6892                            reportSettingsProblem(Log.WARN, msg);
6893                        }
6894                    }
6895                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6896                            || (scanFlags&SCAN_BOOTING) != 0)) {
6897                        // If this is a system app, we can at least delete its
6898                        // current data so the application will still work.
6899                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6900                        if (ret >= 0) {
6901                            // TODO: Kill the processes first
6902                            // Old data gone!
6903                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6904                                    ? "System package " : "Third party package ";
6905                            String msg = prefix + pkg.packageName
6906                                    + " has changed from uid: "
6907                                    + currentUid + " to "
6908                                    + pkg.applicationInfo.uid + "; old data erased";
6909                            reportSettingsProblem(Log.WARN, msg);
6910                            recovered = true;
6911
6912                            // And now re-install the app.
6913                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6914                                    pkg.applicationInfo.seinfo);
6915                            if (ret == -1) {
6916                                // Ack should not happen!
6917                                msg = prefix + pkg.packageName
6918                                        + " could not have data directory re-created after delete.";
6919                                reportSettingsProblem(Log.WARN, msg);
6920                                throw new PackageManagerException(
6921                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6922                            }
6923                        }
6924                        if (!recovered) {
6925                            mHasSystemUidErrors = true;
6926                        }
6927                    } else if (!recovered) {
6928                        // If we allow this install to proceed, we will be broken.
6929                        // Abort, abort!
6930                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6931                                "scanPackageLI");
6932                    }
6933                    if (!recovered) {
6934                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6935                            + pkg.applicationInfo.uid + "/fs_"
6936                            + currentUid;
6937                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6938                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6939                        String msg = "Package " + pkg.packageName
6940                                + " has mismatched uid: "
6941                                + currentUid + " on disk, "
6942                                + pkg.applicationInfo.uid + " in settings";
6943                        // writer
6944                        synchronized (mPackages) {
6945                            mSettings.mReadMessages.append(msg);
6946                            mSettings.mReadMessages.append('\n');
6947                            uidError = true;
6948                            if (!pkgSetting.uidError) {
6949                                reportSettingsProblem(Log.ERROR, msg);
6950                            }
6951                        }
6952                    }
6953                }
6954                pkg.applicationInfo.dataDir = dataPath.getPath();
6955                if (mShouldRestoreconData) {
6956                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6957                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6958                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6959                }
6960            } else {
6961                if (DEBUG_PACKAGE_SCANNING) {
6962                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6963                        Log.v(TAG, "Want this data dir: " + dataPath);
6964                }
6965                //invoke installer to do the actual installation
6966                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6967                        pkg.applicationInfo.seinfo);
6968                if (ret < 0) {
6969                    // Error from installer
6970                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6971                            "Unable to create data dirs [errorCode=" + ret + "]");
6972                }
6973
6974                if (dataPath.exists()) {
6975                    pkg.applicationInfo.dataDir = dataPath.getPath();
6976                } else {
6977                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6978                    pkg.applicationInfo.dataDir = null;
6979                }
6980            }
6981
6982            pkgSetting.uidError = uidError;
6983        }
6984
6985        final String path = scanFile.getPath();
6986        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6987
6988        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6989            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6990
6991            // Some system apps still use directory structure for native libraries
6992            // in which case we might end up not detecting abi solely based on apk
6993            // structure. Try to detect abi based on directory structure.
6994            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6995                    pkg.applicationInfo.primaryCpuAbi == null) {
6996                setBundledAppAbisAndRoots(pkg, pkgSetting);
6997                setNativeLibraryPaths(pkg);
6998            }
6999
7000        } else {
7001            if ((scanFlags & SCAN_MOVE) != 0) {
7002                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7003                // but we already have this packages package info in the PackageSetting. We just
7004                // use that and derive the native library path based on the new codepath.
7005                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7006                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7007            }
7008
7009            // Set native library paths again. For moves, the path will be updated based on the
7010            // ABIs we've determined above. For non-moves, the path will be updated based on the
7011            // ABIs we determined during compilation, but the path will depend on the final
7012            // package path (after the rename away from the stage path).
7013            setNativeLibraryPaths(pkg);
7014        }
7015
7016        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7017        final int[] userIds = sUserManager.getUserIds();
7018        synchronized (mInstallLock) {
7019            // Make sure all user data directories are ready to roll; we're okay
7020            // if they already exist
7021            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7022                for (int userId : userIds) {
7023                    if (userId != 0) {
7024                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7025                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7026                                pkg.applicationInfo.seinfo);
7027                    }
7028                }
7029            }
7030
7031            // Create a native library symlink only if we have native libraries
7032            // and if the native libraries are 32 bit libraries. We do not provide
7033            // this symlink for 64 bit libraries.
7034            if (pkg.applicationInfo.primaryCpuAbi != null &&
7035                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7036                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7037                for (int userId : userIds) {
7038                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7039                            nativeLibPath, userId) < 0) {
7040                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7041                                "Failed linking native library dir (user=" + userId + ")");
7042                    }
7043                }
7044            }
7045        }
7046
7047        // This is a special case for the "system" package, where the ABI is
7048        // dictated by the zygote configuration (and init.rc). We should keep track
7049        // of this ABI so that we can deal with "normal" applications that run under
7050        // the same UID correctly.
7051        if (mPlatformPackage == pkg) {
7052            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7053                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7054        }
7055
7056        // If there's a mismatch between the abi-override in the package setting
7057        // and the abiOverride specified for the install. Warn about this because we
7058        // would've already compiled the app without taking the package setting into
7059        // account.
7060        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7061            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7062                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7063                        " for package: " + pkg.packageName);
7064            }
7065        }
7066
7067        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7068        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7069        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7070
7071        // Copy the derived override back to the parsed package, so that we can
7072        // update the package settings accordingly.
7073        pkg.cpuAbiOverride = cpuAbiOverride;
7074
7075        if (DEBUG_ABI_SELECTION) {
7076            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7077                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7078                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7079        }
7080
7081        // Push the derived path down into PackageSettings so we know what to
7082        // clean up at uninstall time.
7083        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7084
7085        if (DEBUG_ABI_SELECTION) {
7086            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7087                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7088                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7089        }
7090
7091        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7092            // We don't do this here during boot because we can do it all
7093            // at once after scanning all existing packages.
7094            //
7095            // We also do this *before* we perform dexopt on this package, so that
7096            // we can avoid redundant dexopts, and also to make sure we've got the
7097            // code and package path correct.
7098            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7099                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7100        }
7101
7102        if ((scanFlags & SCAN_NO_DEX) == 0) {
7103            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7104                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7105                    (scanFlags & SCAN_BOOTING) == 0);
7106            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7107                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7108            }
7109        }
7110        if (mFactoryTest && pkg.requestedPermissions.contains(
7111                android.Manifest.permission.FACTORY_TEST)) {
7112            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7113        }
7114
7115        ArrayList<PackageParser.Package> clientLibPkgs = null;
7116
7117        // writer
7118        synchronized (mPackages) {
7119            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7120                // Only system apps can add new shared libraries.
7121                if (pkg.libraryNames != null) {
7122                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7123                        String name = pkg.libraryNames.get(i);
7124                        boolean allowed = false;
7125                        if (pkg.isUpdatedSystemApp()) {
7126                            // New library entries can only be added through the
7127                            // system image.  This is important to get rid of a lot
7128                            // of nasty edge cases: for example if we allowed a non-
7129                            // system update of the app to add a library, then uninstalling
7130                            // the update would make the library go away, and assumptions
7131                            // we made such as through app install filtering would now
7132                            // have allowed apps on the device which aren't compatible
7133                            // with it.  Better to just have the restriction here, be
7134                            // conservative, and create many fewer cases that can negatively
7135                            // impact the user experience.
7136                            final PackageSetting sysPs = mSettings
7137                                    .getDisabledSystemPkgLPr(pkg.packageName);
7138                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7139                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7140                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7141                                        allowed = true;
7142                                        allowed = true;
7143                                        break;
7144                                    }
7145                                }
7146                            }
7147                        } else {
7148                            allowed = true;
7149                        }
7150                        if (allowed) {
7151                            if (!mSharedLibraries.containsKey(name)) {
7152                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7153                            } else if (!name.equals(pkg.packageName)) {
7154                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7155                                        + name + " already exists; skipping");
7156                            }
7157                        } else {
7158                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7159                                    + name + " that is not declared on system image; skipping");
7160                        }
7161                    }
7162                    if ((scanFlags&SCAN_BOOTING) == 0) {
7163                        // If we are not booting, we need to update any applications
7164                        // that are clients of our shared library.  If we are booting,
7165                        // this will all be done once the scan is complete.
7166                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7167                    }
7168                }
7169            }
7170        }
7171
7172        // We also need to dexopt any apps that are dependent on this library.  Note that
7173        // if these fail, we should abort the install since installing the library will
7174        // result in some apps being broken.
7175        if (clientLibPkgs != null) {
7176            if ((scanFlags & SCAN_NO_DEX) == 0) {
7177                for (int i = 0; i < clientLibPkgs.size(); i++) {
7178                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7179                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7180                            null /* instruction sets */, forceDex,
7181                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7182                            (scanFlags & SCAN_BOOTING) == 0);
7183                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7184                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7185                                "scanPackageLI failed to dexopt clientLibPkgs");
7186                    }
7187                }
7188            }
7189        }
7190
7191        // Request the ActivityManager to kill the process(only for existing packages)
7192        // so that we do not end up in a confused state while the user is still using the older
7193        // version of the application while the new one gets installed.
7194        if ((scanFlags & SCAN_REPLACING) != 0) {
7195            killApplication(pkg.applicationInfo.packageName,
7196                        pkg.applicationInfo.uid, "replace pkg");
7197        }
7198
7199        // Also need to kill any apps that are dependent on the library.
7200        if (clientLibPkgs != null) {
7201            for (int i=0; i<clientLibPkgs.size(); i++) {
7202                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7203                killApplication(clientPkg.applicationInfo.packageName,
7204                        clientPkg.applicationInfo.uid, "update lib");
7205            }
7206        }
7207
7208        // Make sure we're not adding any bogus keyset info
7209        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7210        ksms.assertScannedPackageValid(pkg);
7211
7212        // writer
7213        synchronized (mPackages) {
7214            // We don't expect installation to fail beyond this point
7215
7216            // Add the new setting to mSettings
7217            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7218            // Add the new setting to mPackages
7219            mPackages.put(pkg.applicationInfo.packageName, pkg);
7220            // Make sure we don't accidentally delete its data.
7221            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7222            while (iter.hasNext()) {
7223                PackageCleanItem item = iter.next();
7224                if (pkgName.equals(item.packageName)) {
7225                    iter.remove();
7226                }
7227            }
7228
7229            // Take care of first install / last update times.
7230            if (currentTime != 0) {
7231                if (pkgSetting.firstInstallTime == 0) {
7232                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7233                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7234                    pkgSetting.lastUpdateTime = currentTime;
7235                }
7236            } else if (pkgSetting.firstInstallTime == 0) {
7237                // We need *something*.  Take time time stamp of the file.
7238                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7239            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7240                if (scanFileTime != pkgSetting.timeStamp) {
7241                    // A package on the system image has changed; consider this
7242                    // to be an update.
7243                    pkgSetting.lastUpdateTime = scanFileTime;
7244                }
7245            }
7246
7247            // Add the package's KeySets to the global KeySetManagerService
7248            ksms.addScannedPackageLPw(pkg);
7249
7250            int N = pkg.providers.size();
7251            StringBuilder r = null;
7252            int i;
7253            for (i=0; i<N; i++) {
7254                PackageParser.Provider p = pkg.providers.get(i);
7255                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7256                        p.info.processName, pkg.applicationInfo.uid);
7257                mProviders.addProvider(p);
7258                p.syncable = p.info.isSyncable;
7259                if (p.info.authority != null) {
7260                    String names[] = p.info.authority.split(";");
7261                    p.info.authority = null;
7262                    for (int j = 0; j < names.length; j++) {
7263                        if (j == 1 && p.syncable) {
7264                            // We only want the first authority for a provider to possibly be
7265                            // syncable, so if we already added this provider using a different
7266                            // authority clear the syncable flag. We copy the provider before
7267                            // changing it because the mProviders object contains a reference
7268                            // to a provider that we don't want to change.
7269                            // Only do this for the second authority since the resulting provider
7270                            // object can be the same for all future authorities for this provider.
7271                            p = new PackageParser.Provider(p);
7272                            p.syncable = false;
7273                        }
7274                        if (!mProvidersByAuthority.containsKey(names[j])) {
7275                            mProvidersByAuthority.put(names[j], p);
7276                            if (p.info.authority == null) {
7277                                p.info.authority = names[j];
7278                            } else {
7279                                p.info.authority = p.info.authority + ";" + names[j];
7280                            }
7281                            if (DEBUG_PACKAGE_SCANNING) {
7282                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7283                                    Log.d(TAG, "Registered content provider: " + names[j]
7284                                            + ", className = " + p.info.name + ", isSyncable = "
7285                                            + p.info.isSyncable);
7286                            }
7287                        } else {
7288                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7289                            Slog.w(TAG, "Skipping provider name " + names[j] +
7290                                    " (in package " + pkg.applicationInfo.packageName +
7291                                    "): name already used by "
7292                                    + ((other != null && other.getComponentName() != null)
7293                                            ? other.getComponentName().getPackageName() : "?"));
7294                        }
7295                    }
7296                }
7297                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7298                    if (r == null) {
7299                        r = new StringBuilder(256);
7300                    } else {
7301                        r.append(' ');
7302                    }
7303                    r.append(p.info.name);
7304                }
7305            }
7306            if (r != null) {
7307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7308            }
7309
7310            N = pkg.services.size();
7311            r = null;
7312            for (i=0; i<N; i++) {
7313                PackageParser.Service s = pkg.services.get(i);
7314                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7315                        s.info.processName, pkg.applicationInfo.uid);
7316                mServices.addService(s);
7317                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7318                    if (r == null) {
7319                        r = new StringBuilder(256);
7320                    } else {
7321                        r.append(' ');
7322                    }
7323                    r.append(s.info.name);
7324                }
7325            }
7326            if (r != null) {
7327                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7328            }
7329
7330            N = pkg.receivers.size();
7331            r = null;
7332            for (i=0; i<N; i++) {
7333                PackageParser.Activity a = pkg.receivers.get(i);
7334                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7335                        a.info.processName, pkg.applicationInfo.uid);
7336                mReceivers.addActivity(a, "receiver");
7337                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7338                    if (r == null) {
7339                        r = new StringBuilder(256);
7340                    } else {
7341                        r.append(' ');
7342                    }
7343                    r.append(a.info.name);
7344                }
7345            }
7346            if (r != null) {
7347                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7348            }
7349
7350            N = pkg.activities.size();
7351            r = null;
7352            for (i=0; i<N; i++) {
7353                PackageParser.Activity a = pkg.activities.get(i);
7354                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7355                        a.info.processName, pkg.applicationInfo.uid);
7356                mActivities.addActivity(a, "activity");
7357                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7358                    if (r == null) {
7359                        r = new StringBuilder(256);
7360                    } else {
7361                        r.append(' ');
7362                    }
7363                    r.append(a.info.name);
7364                }
7365            }
7366            if (r != null) {
7367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7368            }
7369
7370            N = pkg.permissionGroups.size();
7371            r = null;
7372            for (i=0; i<N; i++) {
7373                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7374                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7375                if (cur == null) {
7376                    mPermissionGroups.put(pg.info.name, pg);
7377                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7378                        if (r == null) {
7379                            r = new StringBuilder(256);
7380                        } else {
7381                            r.append(' ');
7382                        }
7383                        r.append(pg.info.name);
7384                    }
7385                } else {
7386                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7387                            + pg.info.packageName + " ignored: original from "
7388                            + cur.info.packageName);
7389                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7390                        if (r == null) {
7391                            r = new StringBuilder(256);
7392                        } else {
7393                            r.append(' ');
7394                        }
7395                        r.append("DUP:");
7396                        r.append(pg.info.name);
7397                    }
7398                }
7399            }
7400            if (r != null) {
7401                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7402            }
7403
7404            N = pkg.permissions.size();
7405            r = null;
7406            for (i=0; i<N; i++) {
7407                PackageParser.Permission p = pkg.permissions.get(i);
7408
7409                // Assume by default that we did not install this permission into the system.
7410                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7411
7412                // Now that permission groups have a special meaning, we ignore permission
7413                // groups for legacy apps to prevent unexpected behavior. In particular,
7414                // permissions for one app being granted to someone just becuase they happen
7415                // to be in a group defined by another app (before this had no implications).
7416                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7417                    p.group = mPermissionGroups.get(p.info.group);
7418                    // Warn for a permission in an unknown group.
7419                    if (p.info.group != null && p.group == null) {
7420                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7421                                + p.info.packageName + " in an unknown group " + p.info.group);
7422                    }
7423                }
7424
7425                ArrayMap<String, BasePermission> permissionMap =
7426                        p.tree ? mSettings.mPermissionTrees
7427                                : mSettings.mPermissions;
7428                BasePermission bp = permissionMap.get(p.info.name);
7429
7430                // Allow system apps to redefine non-system permissions
7431                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7432                    final boolean currentOwnerIsSystem = (bp.perm != null
7433                            && isSystemApp(bp.perm.owner));
7434                    if (isSystemApp(p.owner)) {
7435                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7436                            // It's a built-in permission and no owner, take ownership now
7437                            bp.packageSetting = pkgSetting;
7438                            bp.perm = p;
7439                            bp.uid = pkg.applicationInfo.uid;
7440                            bp.sourcePackage = p.info.packageName;
7441                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7442                        } else if (!currentOwnerIsSystem) {
7443                            String msg = "New decl " + p.owner + " of permission  "
7444                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7445                            reportSettingsProblem(Log.WARN, msg);
7446                            bp = null;
7447                        }
7448                    }
7449                }
7450
7451                if (bp == null) {
7452                    bp = new BasePermission(p.info.name, p.info.packageName,
7453                            BasePermission.TYPE_NORMAL);
7454                    permissionMap.put(p.info.name, bp);
7455                }
7456
7457                if (bp.perm == null) {
7458                    if (bp.sourcePackage == null
7459                            || bp.sourcePackage.equals(p.info.packageName)) {
7460                        BasePermission tree = findPermissionTreeLP(p.info.name);
7461                        if (tree == null
7462                                || tree.sourcePackage.equals(p.info.packageName)) {
7463                            bp.packageSetting = pkgSetting;
7464                            bp.perm = p;
7465                            bp.uid = pkg.applicationInfo.uid;
7466                            bp.sourcePackage = p.info.packageName;
7467                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7468                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7469                                if (r == null) {
7470                                    r = new StringBuilder(256);
7471                                } else {
7472                                    r.append(' ');
7473                                }
7474                                r.append(p.info.name);
7475                            }
7476                        } else {
7477                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7478                                    + p.info.packageName + " ignored: base tree "
7479                                    + tree.name + " is from package "
7480                                    + tree.sourcePackage);
7481                        }
7482                    } else {
7483                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7484                                + p.info.packageName + " ignored: original from "
7485                                + bp.sourcePackage);
7486                    }
7487                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7488                    if (r == null) {
7489                        r = new StringBuilder(256);
7490                    } else {
7491                        r.append(' ');
7492                    }
7493                    r.append("DUP:");
7494                    r.append(p.info.name);
7495                }
7496                if (bp.perm == p) {
7497                    bp.protectionLevel = p.info.protectionLevel;
7498                }
7499            }
7500
7501            if (r != null) {
7502                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7503            }
7504
7505            N = pkg.instrumentation.size();
7506            r = null;
7507            for (i=0; i<N; i++) {
7508                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7509                a.info.packageName = pkg.applicationInfo.packageName;
7510                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7511                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7512                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7513                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7514                a.info.dataDir = pkg.applicationInfo.dataDir;
7515
7516                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7517                // need other information about the application, like the ABI and what not ?
7518                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7519                mInstrumentation.put(a.getComponentName(), a);
7520                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7521                    if (r == null) {
7522                        r = new StringBuilder(256);
7523                    } else {
7524                        r.append(' ');
7525                    }
7526                    r.append(a.info.name);
7527                }
7528            }
7529            if (r != null) {
7530                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7531            }
7532
7533            if (pkg.protectedBroadcasts != null) {
7534                N = pkg.protectedBroadcasts.size();
7535                for (i=0; i<N; i++) {
7536                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7537                }
7538            }
7539
7540            pkgSetting.setTimeStamp(scanFileTime);
7541
7542            // Create idmap files for pairs of (packages, overlay packages).
7543            // Note: "android", ie framework-res.apk, is handled by native layers.
7544            if (pkg.mOverlayTarget != null) {
7545                // This is an overlay package.
7546                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7547                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7548                        mOverlays.put(pkg.mOverlayTarget,
7549                                new ArrayMap<String, PackageParser.Package>());
7550                    }
7551                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7552                    map.put(pkg.packageName, pkg);
7553                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7554                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7555                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7556                                "scanPackageLI failed to createIdmap");
7557                    }
7558                }
7559            } else if (mOverlays.containsKey(pkg.packageName) &&
7560                    !pkg.packageName.equals("android")) {
7561                // This is a regular package, with one or more known overlay packages.
7562                createIdmapsForPackageLI(pkg);
7563            }
7564        }
7565
7566        return pkg;
7567    }
7568
7569    /**
7570     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7571     * is derived purely on the basis of the contents of {@code scanFile} and
7572     * {@code cpuAbiOverride}.
7573     *
7574     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7575     */
7576    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7577                                 String cpuAbiOverride, boolean extractLibs)
7578            throws PackageManagerException {
7579        // TODO: We can probably be smarter about this stuff. For installed apps,
7580        // we can calculate this information at install time once and for all. For
7581        // system apps, we can probably assume that this information doesn't change
7582        // after the first boot scan. As things stand, we do lots of unnecessary work.
7583
7584        // Give ourselves some initial paths; we'll come back for another
7585        // pass once we've determined ABI below.
7586        setNativeLibraryPaths(pkg);
7587
7588        // We would never need to extract libs for forward-locked and external packages,
7589        // since the container service will do it for us. We shouldn't attempt to
7590        // extract libs from system app when it was not updated.
7591        if (pkg.isForwardLocked() || isExternal(pkg) ||
7592            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7593            extractLibs = false;
7594        }
7595
7596        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7597        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7598
7599        NativeLibraryHelper.Handle handle = null;
7600        try {
7601            handle = NativeLibraryHelper.Handle.create(scanFile);
7602            // TODO(multiArch): This can be null for apps that didn't go through the
7603            // usual installation process. We can calculate it again, like we
7604            // do during install time.
7605            //
7606            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7607            // unnecessary.
7608            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7609
7610            // Null out the abis so that they can be recalculated.
7611            pkg.applicationInfo.primaryCpuAbi = null;
7612            pkg.applicationInfo.secondaryCpuAbi = null;
7613            if (isMultiArch(pkg.applicationInfo)) {
7614                // Warn if we've set an abiOverride for multi-lib packages..
7615                // By definition, we need to copy both 32 and 64 bit libraries for
7616                // such packages.
7617                if (pkg.cpuAbiOverride != null
7618                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7619                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7620                }
7621
7622                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7623                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7624                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7625                    if (extractLibs) {
7626                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7627                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7628                                useIsaSpecificSubdirs);
7629                    } else {
7630                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7631                    }
7632                }
7633
7634                maybeThrowExceptionForMultiArchCopy(
7635                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7636
7637                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7638                    if (extractLibs) {
7639                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7640                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7641                                useIsaSpecificSubdirs);
7642                    } else {
7643                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7644                    }
7645                }
7646
7647                maybeThrowExceptionForMultiArchCopy(
7648                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7649
7650                if (abi64 >= 0) {
7651                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7652                }
7653
7654                if (abi32 >= 0) {
7655                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7656                    if (abi64 >= 0) {
7657                        pkg.applicationInfo.secondaryCpuAbi = abi;
7658                    } else {
7659                        pkg.applicationInfo.primaryCpuAbi = abi;
7660                    }
7661                }
7662            } else {
7663                String[] abiList = (cpuAbiOverride != null) ?
7664                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7665
7666                // Enable gross and lame hacks for apps that are built with old
7667                // SDK tools. We must scan their APKs for renderscript bitcode and
7668                // not launch them if it's present. Don't bother checking on devices
7669                // that don't have 64 bit support.
7670                boolean needsRenderScriptOverride = false;
7671                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7672                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7673                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7674                    needsRenderScriptOverride = true;
7675                }
7676
7677                final int copyRet;
7678                if (extractLibs) {
7679                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7680                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7681                } else {
7682                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7683                }
7684
7685                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7686                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7687                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7688                }
7689
7690                if (copyRet >= 0) {
7691                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7692                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7693                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7694                } else if (needsRenderScriptOverride) {
7695                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7696                }
7697            }
7698        } catch (IOException ioe) {
7699            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7700        } finally {
7701            IoUtils.closeQuietly(handle);
7702        }
7703
7704        // Now that we've calculated the ABIs and determined if it's an internal app,
7705        // we will go ahead and populate the nativeLibraryPath.
7706        setNativeLibraryPaths(pkg);
7707    }
7708
7709    /**
7710     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7711     * i.e, so that all packages can be run inside a single process if required.
7712     *
7713     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7714     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7715     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7716     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7717     * updating a package that belongs to a shared user.
7718     *
7719     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7720     * adds unnecessary complexity.
7721     */
7722    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7723            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7724            boolean bootComplete) {
7725        String requiredInstructionSet = null;
7726        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7727            requiredInstructionSet = VMRuntime.getInstructionSet(
7728                     scannedPackage.applicationInfo.primaryCpuAbi);
7729        }
7730
7731        PackageSetting requirer = null;
7732        for (PackageSetting ps : packagesForUser) {
7733            // If packagesForUser contains scannedPackage, we skip it. This will happen
7734            // when scannedPackage is an update of an existing package. Without this check,
7735            // we will never be able to change the ABI of any package belonging to a shared
7736            // user, even if it's compatible with other packages.
7737            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7738                if (ps.primaryCpuAbiString == null) {
7739                    continue;
7740                }
7741
7742                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7743                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7744                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7745                    // this but there's not much we can do.
7746                    String errorMessage = "Instruction set mismatch, "
7747                            + ((requirer == null) ? "[caller]" : requirer)
7748                            + " requires " + requiredInstructionSet + " whereas " + ps
7749                            + " requires " + instructionSet;
7750                    Slog.w(TAG, errorMessage);
7751                }
7752
7753                if (requiredInstructionSet == null) {
7754                    requiredInstructionSet = instructionSet;
7755                    requirer = ps;
7756                }
7757            }
7758        }
7759
7760        if (requiredInstructionSet != null) {
7761            String adjustedAbi;
7762            if (requirer != null) {
7763                // requirer != null implies that either scannedPackage was null or that scannedPackage
7764                // did not require an ABI, in which case we have to adjust scannedPackage to match
7765                // the ABI of the set (which is the same as requirer's ABI)
7766                adjustedAbi = requirer.primaryCpuAbiString;
7767                if (scannedPackage != null) {
7768                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7769                }
7770            } else {
7771                // requirer == null implies that we're updating all ABIs in the set to
7772                // match scannedPackage.
7773                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7774            }
7775
7776            for (PackageSetting ps : packagesForUser) {
7777                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7778                    if (ps.primaryCpuAbiString != null) {
7779                        continue;
7780                    }
7781
7782                    ps.primaryCpuAbiString = adjustedAbi;
7783                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7784                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7785                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7786
7787                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7788                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7789                                bootComplete);
7790                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7791                            ps.primaryCpuAbiString = null;
7792                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7793                            return;
7794                        } else {
7795                            mInstaller.rmdex(ps.codePathString,
7796                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7797                        }
7798                    }
7799                }
7800            }
7801        }
7802    }
7803
7804    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7805        synchronized (mPackages) {
7806            mResolverReplaced = true;
7807            // Set up information for custom user intent resolution activity.
7808            mResolveActivity.applicationInfo = pkg.applicationInfo;
7809            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7810            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7811            mResolveActivity.processName = pkg.applicationInfo.packageName;
7812            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7813            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7814                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7815            mResolveActivity.theme = 0;
7816            mResolveActivity.exported = true;
7817            mResolveActivity.enabled = true;
7818            mResolveInfo.activityInfo = mResolveActivity;
7819            mResolveInfo.priority = 0;
7820            mResolveInfo.preferredOrder = 0;
7821            mResolveInfo.match = 0;
7822            mResolveComponentName = mCustomResolverComponentName;
7823            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7824                    mResolveComponentName);
7825        }
7826    }
7827
7828    private static String calculateBundledApkRoot(final String codePathString) {
7829        final File codePath = new File(codePathString);
7830        final File codeRoot;
7831        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7832            codeRoot = Environment.getRootDirectory();
7833        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7834            codeRoot = Environment.getOemDirectory();
7835        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7836            codeRoot = Environment.getVendorDirectory();
7837        } else {
7838            // Unrecognized code path; take its top real segment as the apk root:
7839            // e.g. /something/app/blah.apk => /something
7840            try {
7841                File f = codePath.getCanonicalFile();
7842                File parent = f.getParentFile();    // non-null because codePath is a file
7843                File tmp;
7844                while ((tmp = parent.getParentFile()) != null) {
7845                    f = parent;
7846                    parent = tmp;
7847                }
7848                codeRoot = f;
7849                Slog.w(TAG, "Unrecognized code path "
7850                        + codePath + " - using " + codeRoot);
7851            } catch (IOException e) {
7852                // Can't canonicalize the code path -- shenanigans?
7853                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7854                return Environment.getRootDirectory().getPath();
7855            }
7856        }
7857        return codeRoot.getPath();
7858    }
7859
7860    /**
7861     * Derive and set the location of native libraries for the given package,
7862     * which varies depending on where and how the package was installed.
7863     */
7864    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7865        final ApplicationInfo info = pkg.applicationInfo;
7866        final String codePath = pkg.codePath;
7867        final File codeFile = new File(codePath);
7868        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7869        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7870
7871        info.nativeLibraryRootDir = null;
7872        info.nativeLibraryRootRequiresIsa = false;
7873        info.nativeLibraryDir = null;
7874        info.secondaryNativeLibraryDir = null;
7875
7876        if (isApkFile(codeFile)) {
7877            // Monolithic install
7878            if (bundledApp) {
7879                // If "/system/lib64/apkname" exists, assume that is the per-package
7880                // native library directory to use; otherwise use "/system/lib/apkname".
7881                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7882                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7883                        getPrimaryInstructionSet(info));
7884
7885                // This is a bundled system app so choose the path based on the ABI.
7886                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7887                // is just the default path.
7888                final String apkName = deriveCodePathName(codePath);
7889                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7890                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7891                        apkName).getAbsolutePath();
7892
7893                if (info.secondaryCpuAbi != null) {
7894                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7895                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7896                            secondaryLibDir, apkName).getAbsolutePath();
7897                }
7898            } else if (asecApp) {
7899                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7900                        .getAbsolutePath();
7901            } else {
7902                final String apkName = deriveCodePathName(codePath);
7903                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7904                        .getAbsolutePath();
7905            }
7906
7907            info.nativeLibraryRootRequiresIsa = false;
7908            info.nativeLibraryDir = info.nativeLibraryRootDir;
7909        } else {
7910            // Cluster install
7911            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7912            info.nativeLibraryRootRequiresIsa = true;
7913
7914            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7915                    getPrimaryInstructionSet(info)).getAbsolutePath();
7916
7917            if (info.secondaryCpuAbi != null) {
7918                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7919                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7920            }
7921        }
7922    }
7923
7924    /**
7925     * Calculate the abis and roots for a bundled app. These can uniquely
7926     * be determined from the contents of the system partition, i.e whether
7927     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7928     * of this information, and instead assume that the system was built
7929     * sensibly.
7930     */
7931    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7932                                           PackageSetting pkgSetting) {
7933        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7934
7935        // If "/system/lib64/apkname" exists, assume that is the per-package
7936        // native library directory to use; otherwise use "/system/lib/apkname".
7937        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7938        setBundledAppAbi(pkg, apkRoot, apkName);
7939        // pkgSetting might be null during rescan following uninstall of updates
7940        // to a bundled app, so accommodate that possibility.  The settings in
7941        // that case will be established later from the parsed package.
7942        //
7943        // If the settings aren't null, sync them up with what we've just derived.
7944        // note that apkRoot isn't stored in the package settings.
7945        if (pkgSetting != null) {
7946            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7947            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7948        }
7949    }
7950
7951    /**
7952     * Deduces the ABI of a bundled app and sets the relevant fields on the
7953     * parsed pkg object.
7954     *
7955     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7956     *        under which system libraries are installed.
7957     * @param apkName the name of the installed package.
7958     */
7959    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7960        final File codeFile = new File(pkg.codePath);
7961
7962        final boolean has64BitLibs;
7963        final boolean has32BitLibs;
7964        if (isApkFile(codeFile)) {
7965            // Monolithic install
7966            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7967            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7968        } else {
7969            // Cluster install
7970            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7971            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7972                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7973                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7974                has64BitLibs = (new File(rootDir, isa)).exists();
7975            } else {
7976                has64BitLibs = false;
7977            }
7978            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7979                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7980                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7981                has32BitLibs = (new File(rootDir, isa)).exists();
7982            } else {
7983                has32BitLibs = false;
7984            }
7985        }
7986
7987        if (has64BitLibs && !has32BitLibs) {
7988            // The package has 64 bit libs, but not 32 bit libs. Its primary
7989            // ABI should be 64 bit. We can safely assume here that the bundled
7990            // native libraries correspond to the most preferred ABI in the list.
7991
7992            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7993            pkg.applicationInfo.secondaryCpuAbi = null;
7994        } else if (has32BitLibs && !has64BitLibs) {
7995            // The package has 32 bit libs but not 64 bit libs. Its primary
7996            // ABI should be 32 bit.
7997
7998            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7999            pkg.applicationInfo.secondaryCpuAbi = null;
8000        } else if (has32BitLibs && has64BitLibs) {
8001            // The application has both 64 and 32 bit bundled libraries. We check
8002            // here that the app declares multiArch support, and warn if it doesn't.
8003            //
8004            // We will be lenient here and record both ABIs. The primary will be the
8005            // ABI that's higher on the list, i.e, a device that's configured to prefer
8006            // 64 bit apps will see a 64 bit primary ABI,
8007
8008            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8009                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8010            }
8011
8012            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8013                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8014                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8015            } else {
8016                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8017                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8018            }
8019        } else {
8020            pkg.applicationInfo.primaryCpuAbi = null;
8021            pkg.applicationInfo.secondaryCpuAbi = null;
8022        }
8023    }
8024
8025    private void killApplication(String pkgName, int appId, String reason) {
8026        // Request the ActivityManager to kill the process(only for existing packages)
8027        // so that we do not end up in a confused state while the user is still using the older
8028        // version of the application while the new one gets installed.
8029        IActivityManager am = ActivityManagerNative.getDefault();
8030        if (am != null) {
8031            try {
8032                am.killApplicationWithAppId(pkgName, appId, reason);
8033            } catch (RemoteException e) {
8034            }
8035        }
8036    }
8037
8038    void removePackageLI(PackageSetting ps, boolean chatty) {
8039        if (DEBUG_INSTALL) {
8040            if (chatty)
8041                Log.d(TAG, "Removing package " + ps.name);
8042        }
8043
8044        // writer
8045        synchronized (mPackages) {
8046            mPackages.remove(ps.name);
8047            final PackageParser.Package pkg = ps.pkg;
8048            if (pkg != null) {
8049                cleanPackageDataStructuresLILPw(pkg, chatty);
8050            }
8051        }
8052    }
8053
8054    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8055        if (DEBUG_INSTALL) {
8056            if (chatty)
8057                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8058        }
8059
8060        // writer
8061        synchronized (mPackages) {
8062            mPackages.remove(pkg.applicationInfo.packageName);
8063            cleanPackageDataStructuresLILPw(pkg, chatty);
8064        }
8065    }
8066
8067    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8068        int N = pkg.providers.size();
8069        StringBuilder r = null;
8070        int i;
8071        for (i=0; i<N; i++) {
8072            PackageParser.Provider p = pkg.providers.get(i);
8073            mProviders.removeProvider(p);
8074            if (p.info.authority == null) {
8075
8076                /* There was another ContentProvider with this authority when
8077                 * this app was installed so this authority is null,
8078                 * Ignore it as we don't have to unregister the provider.
8079                 */
8080                continue;
8081            }
8082            String names[] = p.info.authority.split(";");
8083            for (int j = 0; j < names.length; j++) {
8084                if (mProvidersByAuthority.get(names[j]) == p) {
8085                    mProvidersByAuthority.remove(names[j]);
8086                    if (DEBUG_REMOVE) {
8087                        if (chatty)
8088                            Log.d(TAG, "Unregistered content provider: " + names[j]
8089                                    + ", className = " + p.info.name + ", isSyncable = "
8090                                    + p.info.isSyncable);
8091                    }
8092                }
8093            }
8094            if (DEBUG_REMOVE && chatty) {
8095                if (r == null) {
8096                    r = new StringBuilder(256);
8097                } else {
8098                    r.append(' ');
8099                }
8100                r.append(p.info.name);
8101            }
8102        }
8103        if (r != null) {
8104            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8105        }
8106
8107        N = pkg.services.size();
8108        r = null;
8109        for (i=0; i<N; i++) {
8110            PackageParser.Service s = pkg.services.get(i);
8111            mServices.removeService(s);
8112            if (chatty) {
8113                if (r == null) {
8114                    r = new StringBuilder(256);
8115                } else {
8116                    r.append(' ');
8117                }
8118                r.append(s.info.name);
8119            }
8120        }
8121        if (r != null) {
8122            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8123        }
8124
8125        N = pkg.receivers.size();
8126        r = null;
8127        for (i=0; i<N; i++) {
8128            PackageParser.Activity a = pkg.receivers.get(i);
8129            mReceivers.removeActivity(a, "receiver");
8130            if (DEBUG_REMOVE && chatty) {
8131                if (r == null) {
8132                    r = new StringBuilder(256);
8133                } else {
8134                    r.append(' ');
8135                }
8136                r.append(a.info.name);
8137            }
8138        }
8139        if (r != null) {
8140            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8141        }
8142
8143        N = pkg.activities.size();
8144        r = null;
8145        for (i=0; i<N; i++) {
8146            PackageParser.Activity a = pkg.activities.get(i);
8147            mActivities.removeActivity(a, "activity");
8148            if (DEBUG_REMOVE && chatty) {
8149                if (r == null) {
8150                    r = new StringBuilder(256);
8151                } else {
8152                    r.append(' ');
8153                }
8154                r.append(a.info.name);
8155            }
8156        }
8157        if (r != null) {
8158            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8159        }
8160
8161        N = pkg.permissions.size();
8162        r = null;
8163        for (i=0; i<N; i++) {
8164            PackageParser.Permission p = pkg.permissions.get(i);
8165            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8166            if (bp == null) {
8167                bp = mSettings.mPermissionTrees.get(p.info.name);
8168            }
8169            if (bp != null && bp.perm == p) {
8170                bp.perm = null;
8171                if (DEBUG_REMOVE && chatty) {
8172                    if (r == null) {
8173                        r = new StringBuilder(256);
8174                    } else {
8175                        r.append(' ');
8176                    }
8177                    r.append(p.info.name);
8178                }
8179            }
8180            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8181                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8182                if (appOpPerms != null) {
8183                    appOpPerms.remove(pkg.packageName);
8184                }
8185            }
8186        }
8187        if (r != null) {
8188            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8189        }
8190
8191        N = pkg.requestedPermissions.size();
8192        r = null;
8193        for (i=0; i<N; i++) {
8194            String perm = pkg.requestedPermissions.get(i);
8195            BasePermission bp = mSettings.mPermissions.get(perm);
8196            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8197                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8198                if (appOpPerms != null) {
8199                    appOpPerms.remove(pkg.packageName);
8200                    if (appOpPerms.isEmpty()) {
8201                        mAppOpPermissionPackages.remove(perm);
8202                    }
8203                }
8204            }
8205        }
8206        if (r != null) {
8207            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8208        }
8209
8210        N = pkg.instrumentation.size();
8211        r = null;
8212        for (i=0; i<N; i++) {
8213            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8214            mInstrumentation.remove(a.getComponentName());
8215            if (DEBUG_REMOVE && chatty) {
8216                if (r == null) {
8217                    r = new StringBuilder(256);
8218                } else {
8219                    r.append(' ');
8220                }
8221                r.append(a.info.name);
8222            }
8223        }
8224        if (r != null) {
8225            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8226        }
8227
8228        r = null;
8229        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8230            // Only system apps can hold shared libraries.
8231            if (pkg.libraryNames != null) {
8232                for (i=0; i<pkg.libraryNames.size(); i++) {
8233                    String name = pkg.libraryNames.get(i);
8234                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8235                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8236                        mSharedLibraries.remove(name);
8237                        if (DEBUG_REMOVE && chatty) {
8238                            if (r == null) {
8239                                r = new StringBuilder(256);
8240                            } else {
8241                                r.append(' ');
8242                            }
8243                            r.append(name);
8244                        }
8245                    }
8246                }
8247            }
8248        }
8249        if (r != null) {
8250            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8251        }
8252    }
8253
8254    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8255        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8256            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8257                return true;
8258            }
8259        }
8260        return false;
8261    }
8262
8263    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8264    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8265    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8266
8267    private void updatePermissionsLPw(String changingPkg,
8268            PackageParser.Package pkgInfo, int flags) {
8269        // Make sure there are no dangling permission trees.
8270        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8271        while (it.hasNext()) {
8272            final BasePermission bp = it.next();
8273            if (bp.packageSetting == null) {
8274                // We may not yet have parsed the package, so just see if
8275                // we still know about its settings.
8276                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8277            }
8278            if (bp.packageSetting == null) {
8279                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8280                        + " from package " + bp.sourcePackage);
8281                it.remove();
8282            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8283                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8284                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8285                            + " from package " + bp.sourcePackage);
8286                    flags |= UPDATE_PERMISSIONS_ALL;
8287                    it.remove();
8288                }
8289            }
8290        }
8291
8292        // Make sure all dynamic permissions have been assigned to a package,
8293        // and make sure there are no dangling permissions.
8294        it = mSettings.mPermissions.values().iterator();
8295        while (it.hasNext()) {
8296            final BasePermission bp = it.next();
8297            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8298                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8299                        + bp.name + " pkg=" + bp.sourcePackage
8300                        + " info=" + bp.pendingInfo);
8301                if (bp.packageSetting == null && bp.pendingInfo != null) {
8302                    final BasePermission tree = findPermissionTreeLP(bp.name);
8303                    if (tree != null && tree.perm != null) {
8304                        bp.packageSetting = tree.packageSetting;
8305                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8306                                new PermissionInfo(bp.pendingInfo));
8307                        bp.perm.info.packageName = tree.perm.info.packageName;
8308                        bp.perm.info.name = bp.name;
8309                        bp.uid = tree.uid;
8310                    }
8311                }
8312            }
8313            if (bp.packageSetting == null) {
8314                // We may not yet have parsed the package, so just see if
8315                // we still know about its settings.
8316                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8317            }
8318            if (bp.packageSetting == null) {
8319                Slog.w(TAG, "Removing dangling permission: " + bp.name
8320                        + " from package " + bp.sourcePackage);
8321                it.remove();
8322            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8323                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8324                    Slog.i(TAG, "Removing old permission: " + bp.name
8325                            + " from package " + bp.sourcePackage);
8326                    flags |= UPDATE_PERMISSIONS_ALL;
8327                    it.remove();
8328                }
8329            }
8330        }
8331
8332        // Now update the permissions for all packages, in particular
8333        // replace the granted permissions of the system packages.
8334        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8335            for (PackageParser.Package pkg : mPackages.values()) {
8336                if (pkg != pkgInfo) {
8337                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8338                            changingPkg);
8339                }
8340            }
8341        }
8342
8343        if (pkgInfo != null) {
8344            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8345        }
8346    }
8347
8348    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8349            String packageOfInterest) {
8350        // IMPORTANT: There are two types of permissions: install and runtime.
8351        // Install time permissions are granted when the app is installed to
8352        // all device users and users added in the future. Runtime permissions
8353        // are granted at runtime explicitly to specific users. Normal and signature
8354        // protected permissions are install time permissions. Dangerous permissions
8355        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8356        // otherwise they are runtime permissions. This function does not manage
8357        // runtime permissions except for the case an app targeting Lollipop MR1
8358        // being upgraded to target a newer SDK, in which case dangerous permissions
8359        // are transformed from install time to runtime ones.
8360
8361        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8362        if (ps == null) {
8363            return;
8364        }
8365
8366        PermissionsState permissionsState = ps.getPermissionsState();
8367        PermissionsState origPermissions = permissionsState;
8368
8369        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8370
8371        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8372
8373        boolean changedInstallPermission = false;
8374
8375        if (replace) {
8376            ps.installPermissionsFixed = false;
8377            if (!ps.isSharedUser()) {
8378                origPermissions = new PermissionsState(permissionsState);
8379                permissionsState.reset();
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.
8596        for (int userId : changedRuntimePermissionUserIds) {
8597            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8598        }
8599    }
8600
8601    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8602        boolean allowed = false;
8603        final int NP = PackageParser.NEW_PERMISSIONS.length;
8604        for (int ip=0; ip<NP; ip++) {
8605            final PackageParser.NewPermissionInfo npi
8606                    = PackageParser.NEW_PERMISSIONS[ip];
8607            if (npi.name.equals(perm)
8608                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8609                allowed = true;
8610                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8611                        + pkg.packageName);
8612                break;
8613            }
8614        }
8615        return allowed;
8616    }
8617
8618    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8619            BasePermission bp, PermissionsState origPermissions) {
8620        boolean allowed;
8621        allowed = (compareSignatures(
8622                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8623                        == PackageManager.SIGNATURE_MATCH)
8624                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8625                        == PackageManager.SIGNATURE_MATCH);
8626        if (!allowed && (bp.protectionLevel
8627                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8628            if (isSystemApp(pkg)) {
8629                // For updated system applications, a system permission
8630                // is granted only if it had been defined by the original application.
8631                if (pkg.isUpdatedSystemApp()) {
8632                    final PackageSetting sysPs = mSettings
8633                            .getDisabledSystemPkgLPr(pkg.packageName);
8634                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8635                        // If the original was granted this permission, we take
8636                        // that grant decision as read and propagate it to the
8637                        // update.
8638                        if (sysPs.isPrivileged()) {
8639                            allowed = true;
8640                        }
8641                    } else {
8642                        // The system apk may have been updated with an older
8643                        // version of the one on the data partition, but which
8644                        // granted a new system permission that it didn't have
8645                        // before.  In this case we do want to allow the app to
8646                        // now get the new permission if the ancestral apk is
8647                        // privileged to get it.
8648                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8649                            for (int j=0;
8650                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8651                                if (perm.equals(
8652                                        sysPs.pkg.requestedPermissions.get(j))) {
8653                                    allowed = true;
8654                                    break;
8655                                }
8656                            }
8657                        }
8658                    }
8659                } else {
8660                    allowed = isPrivilegedApp(pkg);
8661                }
8662            }
8663        }
8664        if (!allowed) {
8665            if (!allowed && (bp.protectionLevel
8666                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8667                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8668                // If this was a previously normal/dangerous permission that got moved
8669                // to a system permission as part of the runtime permission redesign, then
8670                // we still want to blindly grant it to old apps.
8671                allowed = true;
8672            }
8673            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8674                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8675                // If this permission is to be granted to the system installer and
8676                // this app is an installer, then it gets the permission.
8677                allowed = true;
8678            }
8679            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8680                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8681                // If this permission is to be granted to the system verifier and
8682                // this app is a verifier, then it gets the permission.
8683                allowed = true;
8684            }
8685            if (!allowed && (bp.protectionLevel
8686                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8687                    && isSystemApp(pkg)) {
8688                // Any pre-installed system app is allowed to get this permission.
8689                allowed = true;
8690            }
8691            if (!allowed && (bp.protectionLevel
8692                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8693                // For development permissions, a development permission
8694                // is granted only if it was already granted.
8695                allowed = origPermissions.hasInstallPermission(perm);
8696            }
8697        }
8698        return allowed;
8699    }
8700
8701    final class ActivityIntentResolver
8702            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8703        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8704                boolean defaultOnly, int userId) {
8705            if (!sUserManager.exists(userId)) return null;
8706            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8707            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8708        }
8709
8710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8711                int userId) {
8712            if (!sUserManager.exists(userId)) return null;
8713            mFlags = flags;
8714            return super.queryIntent(intent, resolvedType,
8715                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8716        }
8717
8718        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8719                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8720            if (!sUserManager.exists(userId)) return null;
8721            if (packageActivities == null) {
8722                return null;
8723            }
8724            mFlags = flags;
8725            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8726            final int N = packageActivities.size();
8727            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8728                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8729
8730            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8731            for (int i = 0; i < N; ++i) {
8732                intentFilters = packageActivities.get(i).intents;
8733                if (intentFilters != null && intentFilters.size() > 0) {
8734                    PackageParser.ActivityIntentInfo[] array =
8735                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8736                    intentFilters.toArray(array);
8737                    listCut.add(array);
8738                }
8739            }
8740            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8741        }
8742
8743        public final void addActivity(PackageParser.Activity a, String type) {
8744            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8745            mActivities.put(a.getComponentName(), a);
8746            if (DEBUG_SHOW_INFO)
8747                Log.v(
8748                TAG, "  " + type + " " +
8749                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8750            if (DEBUG_SHOW_INFO)
8751                Log.v(TAG, "    Class=" + a.info.name);
8752            final int NI = a.intents.size();
8753            for (int j=0; j<NI; j++) {
8754                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8755                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8756                    intent.setPriority(0);
8757                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8758                            + a.className + " with priority > 0, forcing to 0");
8759                }
8760                if (DEBUG_SHOW_INFO) {
8761                    Log.v(TAG, "    IntentFilter:");
8762                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8763                }
8764                if (!intent.debugCheck()) {
8765                    Log.w(TAG, "==> For Activity " + a.info.name);
8766                }
8767                addFilter(intent);
8768            }
8769        }
8770
8771        public final void removeActivity(PackageParser.Activity a, String type) {
8772            mActivities.remove(a.getComponentName());
8773            if (DEBUG_SHOW_INFO) {
8774                Log.v(TAG, "  " + type + " "
8775                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8776                                : a.info.name) + ":");
8777                Log.v(TAG, "    Class=" + a.info.name);
8778            }
8779            final int NI = a.intents.size();
8780            for (int j=0; j<NI; j++) {
8781                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8782                if (DEBUG_SHOW_INFO) {
8783                    Log.v(TAG, "    IntentFilter:");
8784                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8785                }
8786                removeFilter(intent);
8787            }
8788        }
8789
8790        @Override
8791        protected boolean allowFilterResult(
8792                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8793            ActivityInfo filterAi = filter.activity.info;
8794            for (int i=dest.size()-1; i>=0; i--) {
8795                ActivityInfo destAi = dest.get(i).activityInfo;
8796                if (destAi.name == filterAi.name
8797                        && destAi.packageName == filterAi.packageName) {
8798                    return false;
8799                }
8800            }
8801            return true;
8802        }
8803
8804        @Override
8805        protected ActivityIntentInfo[] newArray(int size) {
8806            return new ActivityIntentInfo[size];
8807        }
8808
8809        @Override
8810        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8811            if (!sUserManager.exists(userId)) return true;
8812            PackageParser.Package p = filter.activity.owner;
8813            if (p != null) {
8814                PackageSetting ps = (PackageSetting)p.mExtras;
8815                if (ps != null) {
8816                    // System apps are never considered stopped for purposes of
8817                    // filtering, because there may be no way for the user to
8818                    // actually re-launch them.
8819                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8820                            && ps.getStopped(userId);
8821                }
8822            }
8823            return false;
8824        }
8825
8826        @Override
8827        protected boolean isPackageForFilter(String packageName,
8828                PackageParser.ActivityIntentInfo info) {
8829            return packageName.equals(info.activity.owner.packageName);
8830        }
8831
8832        @Override
8833        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8834                int match, int userId) {
8835            if (!sUserManager.exists(userId)) return null;
8836            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8837                return null;
8838            }
8839            final PackageParser.Activity activity = info.activity;
8840            if (mSafeMode && (activity.info.applicationInfo.flags
8841                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8842                return null;
8843            }
8844            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8845            if (ps == null) {
8846                return null;
8847            }
8848            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8849                    ps.readUserState(userId), userId);
8850            if (ai == null) {
8851                return null;
8852            }
8853            final ResolveInfo res = new ResolveInfo();
8854            res.activityInfo = ai;
8855            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8856                res.filter = info;
8857            }
8858            if (info != null) {
8859                res.handleAllWebDataURI = info.handleAllWebDataURI();
8860            }
8861            res.priority = info.getPriority();
8862            res.preferredOrder = activity.owner.mPreferredOrder;
8863            //System.out.println("Result: " + res.activityInfo.className +
8864            //                   " = " + res.priority);
8865            res.match = match;
8866            res.isDefault = info.hasDefault;
8867            res.labelRes = info.labelRes;
8868            res.nonLocalizedLabel = info.nonLocalizedLabel;
8869            if (userNeedsBadging(userId)) {
8870                res.noResourceId = true;
8871            } else {
8872                res.icon = info.icon;
8873            }
8874            res.iconResourceId = info.icon;
8875            res.system = res.activityInfo.applicationInfo.isSystemApp();
8876            return res;
8877        }
8878
8879        @Override
8880        protected void sortResults(List<ResolveInfo> results) {
8881            Collections.sort(results, mResolvePrioritySorter);
8882        }
8883
8884        @Override
8885        protected void dumpFilter(PrintWriter out, String prefix,
8886                PackageParser.ActivityIntentInfo filter) {
8887            out.print(prefix); out.print(
8888                    Integer.toHexString(System.identityHashCode(filter.activity)));
8889                    out.print(' ');
8890                    filter.activity.printComponentShortName(out);
8891                    out.print(" filter ");
8892                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8893        }
8894
8895        @Override
8896        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8897            return filter.activity;
8898        }
8899
8900        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8901            PackageParser.Activity activity = (PackageParser.Activity)label;
8902            out.print(prefix); out.print(
8903                    Integer.toHexString(System.identityHashCode(activity)));
8904                    out.print(' ');
8905                    activity.printComponentShortName(out);
8906            if (count > 1) {
8907                out.print(" ("); out.print(count); out.print(" filters)");
8908            }
8909            out.println();
8910        }
8911
8912//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8913//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8914//            final List<ResolveInfo> retList = Lists.newArrayList();
8915//            while (i.hasNext()) {
8916//                final ResolveInfo resolveInfo = i.next();
8917//                if (isEnabledLP(resolveInfo.activityInfo)) {
8918//                    retList.add(resolveInfo);
8919//                }
8920//            }
8921//            return retList;
8922//        }
8923
8924        // Keys are String (activity class name), values are Activity.
8925        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8926                = new ArrayMap<ComponentName, PackageParser.Activity>();
8927        private int mFlags;
8928    }
8929
8930    private final class ServiceIntentResolver
8931            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8932        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8933                boolean defaultOnly, int userId) {
8934            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8935            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8936        }
8937
8938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8939                int userId) {
8940            if (!sUserManager.exists(userId)) return null;
8941            mFlags = flags;
8942            return super.queryIntent(intent, resolvedType,
8943                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8944        }
8945
8946        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8947                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8948            if (!sUserManager.exists(userId)) return null;
8949            if (packageServices == null) {
8950                return null;
8951            }
8952            mFlags = flags;
8953            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8954            final int N = packageServices.size();
8955            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8956                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8957
8958            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8959            for (int i = 0; i < N; ++i) {
8960                intentFilters = packageServices.get(i).intents;
8961                if (intentFilters != null && intentFilters.size() > 0) {
8962                    PackageParser.ServiceIntentInfo[] array =
8963                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8964                    intentFilters.toArray(array);
8965                    listCut.add(array);
8966                }
8967            }
8968            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8969        }
8970
8971        public final void addService(PackageParser.Service s) {
8972            mServices.put(s.getComponentName(), s);
8973            if (DEBUG_SHOW_INFO) {
8974                Log.v(TAG, "  "
8975                        + (s.info.nonLocalizedLabel != null
8976                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8977                Log.v(TAG, "    Class=" + s.info.name);
8978            }
8979            final int NI = s.intents.size();
8980            int j;
8981            for (j=0; j<NI; j++) {
8982                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8983                if (DEBUG_SHOW_INFO) {
8984                    Log.v(TAG, "    IntentFilter:");
8985                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8986                }
8987                if (!intent.debugCheck()) {
8988                    Log.w(TAG, "==> For Service " + s.info.name);
8989                }
8990                addFilter(intent);
8991            }
8992        }
8993
8994        public final void removeService(PackageParser.Service s) {
8995            mServices.remove(s.getComponentName());
8996            if (DEBUG_SHOW_INFO) {
8997                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8998                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8999                Log.v(TAG, "    Class=" + s.info.name);
9000            }
9001            final int NI = s.intents.size();
9002            int j;
9003            for (j=0; j<NI; j++) {
9004                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9005                if (DEBUG_SHOW_INFO) {
9006                    Log.v(TAG, "    IntentFilter:");
9007                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9008                }
9009                removeFilter(intent);
9010            }
9011        }
9012
9013        @Override
9014        protected boolean allowFilterResult(
9015                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9016            ServiceInfo filterSi = filter.service.info;
9017            for (int i=dest.size()-1; i>=0; i--) {
9018                ServiceInfo destAi = dest.get(i).serviceInfo;
9019                if (destAi.name == filterSi.name
9020                        && destAi.packageName == filterSi.packageName) {
9021                    return false;
9022                }
9023            }
9024            return true;
9025        }
9026
9027        @Override
9028        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9029            return new PackageParser.ServiceIntentInfo[size];
9030        }
9031
9032        @Override
9033        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9034            if (!sUserManager.exists(userId)) return true;
9035            PackageParser.Package p = filter.service.owner;
9036            if (p != null) {
9037                PackageSetting ps = (PackageSetting)p.mExtras;
9038                if (ps != null) {
9039                    // System apps are never considered stopped for purposes of
9040                    // filtering, because there may be no way for the user to
9041                    // actually re-launch them.
9042                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9043                            && ps.getStopped(userId);
9044                }
9045            }
9046            return false;
9047        }
9048
9049        @Override
9050        protected boolean isPackageForFilter(String packageName,
9051                PackageParser.ServiceIntentInfo info) {
9052            return packageName.equals(info.service.owner.packageName);
9053        }
9054
9055        @Override
9056        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9057                int match, int userId) {
9058            if (!sUserManager.exists(userId)) return null;
9059            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9060            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9061                return null;
9062            }
9063            final PackageParser.Service service = info.service;
9064            if (mSafeMode && (service.info.applicationInfo.flags
9065                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9066                return null;
9067            }
9068            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9069            if (ps == null) {
9070                return null;
9071            }
9072            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9073                    ps.readUserState(userId), userId);
9074            if (si == null) {
9075                return null;
9076            }
9077            final ResolveInfo res = new ResolveInfo();
9078            res.serviceInfo = si;
9079            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9080                res.filter = filter;
9081            }
9082            res.priority = info.getPriority();
9083            res.preferredOrder = service.owner.mPreferredOrder;
9084            res.match = match;
9085            res.isDefault = info.hasDefault;
9086            res.labelRes = info.labelRes;
9087            res.nonLocalizedLabel = info.nonLocalizedLabel;
9088            res.icon = info.icon;
9089            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9090            return res;
9091        }
9092
9093        @Override
9094        protected void sortResults(List<ResolveInfo> results) {
9095            Collections.sort(results, mResolvePrioritySorter);
9096        }
9097
9098        @Override
9099        protected void dumpFilter(PrintWriter out, String prefix,
9100                PackageParser.ServiceIntentInfo filter) {
9101            out.print(prefix); out.print(
9102                    Integer.toHexString(System.identityHashCode(filter.service)));
9103                    out.print(' ');
9104                    filter.service.printComponentShortName(out);
9105                    out.print(" filter ");
9106                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9107        }
9108
9109        @Override
9110        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9111            return filter.service;
9112        }
9113
9114        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9115            PackageParser.Service service = (PackageParser.Service)label;
9116            out.print(prefix); out.print(
9117                    Integer.toHexString(System.identityHashCode(service)));
9118                    out.print(' ');
9119                    service.printComponentShortName(out);
9120            if (count > 1) {
9121                out.print(" ("); out.print(count); out.print(" filters)");
9122            }
9123            out.println();
9124        }
9125
9126//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9127//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9128//            final List<ResolveInfo> retList = Lists.newArrayList();
9129//            while (i.hasNext()) {
9130//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9131//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9132//                    retList.add(resolveInfo);
9133//                }
9134//            }
9135//            return retList;
9136//        }
9137
9138        // Keys are String (activity class name), values are Activity.
9139        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9140                = new ArrayMap<ComponentName, PackageParser.Service>();
9141        private int mFlags;
9142    };
9143
9144    private final class ProviderIntentResolver
9145            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9146        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9147                boolean defaultOnly, int userId) {
9148            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9149            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9150        }
9151
9152        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9153                int userId) {
9154            if (!sUserManager.exists(userId))
9155                return null;
9156            mFlags = flags;
9157            return super.queryIntent(intent, resolvedType,
9158                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9159        }
9160
9161        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9162                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9163            if (!sUserManager.exists(userId))
9164                return null;
9165            if (packageProviders == null) {
9166                return null;
9167            }
9168            mFlags = flags;
9169            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9170            final int N = packageProviders.size();
9171            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9172                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9173
9174            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9175            for (int i = 0; i < N; ++i) {
9176                intentFilters = packageProviders.get(i).intents;
9177                if (intentFilters != null && intentFilters.size() > 0) {
9178                    PackageParser.ProviderIntentInfo[] array =
9179                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9180                    intentFilters.toArray(array);
9181                    listCut.add(array);
9182                }
9183            }
9184            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9185        }
9186
9187        public final void addProvider(PackageParser.Provider p) {
9188            if (mProviders.containsKey(p.getComponentName())) {
9189                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9190                return;
9191            }
9192
9193            mProviders.put(p.getComponentName(), p);
9194            if (DEBUG_SHOW_INFO) {
9195                Log.v(TAG, "  "
9196                        + (p.info.nonLocalizedLabel != null
9197                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9198                Log.v(TAG, "    Class=" + p.info.name);
9199            }
9200            final int NI = p.intents.size();
9201            int j;
9202            for (j = 0; j < NI; j++) {
9203                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9204                if (DEBUG_SHOW_INFO) {
9205                    Log.v(TAG, "    IntentFilter:");
9206                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9207                }
9208                if (!intent.debugCheck()) {
9209                    Log.w(TAG, "==> For Provider " + p.info.name);
9210                }
9211                addFilter(intent);
9212            }
9213        }
9214
9215        public final void removeProvider(PackageParser.Provider p) {
9216            mProviders.remove(p.getComponentName());
9217            if (DEBUG_SHOW_INFO) {
9218                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9219                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9220                Log.v(TAG, "    Class=" + p.info.name);
9221            }
9222            final int NI = p.intents.size();
9223            int j;
9224            for (j = 0; j < NI; j++) {
9225                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9226                if (DEBUG_SHOW_INFO) {
9227                    Log.v(TAG, "    IntentFilter:");
9228                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9229                }
9230                removeFilter(intent);
9231            }
9232        }
9233
9234        @Override
9235        protected boolean allowFilterResult(
9236                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9237            ProviderInfo filterPi = filter.provider.info;
9238            for (int i = dest.size() - 1; i >= 0; i--) {
9239                ProviderInfo destPi = dest.get(i).providerInfo;
9240                if (destPi.name == filterPi.name
9241                        && destPi.packageName == filterPi.packageName) {
9242                    return false;
9243                }
9244            }
9245            return true;
9246        }
9247
9248        @Override
9249        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9250            return new PackageParser.ProviderIntentInfo[size];
9251        }
9252
9253        @Override
9254        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9255            if (!sUserManager.exists(userId))
9256                return true;
9257            PackageParser.Package p = filter.provider.owner;
9258            if (p != null) {
9259                PackageSetting ps = (PackageSetting) p.mExtras;
9260                if (ps != null) {
9261                    // System apps are never considered stopped for purposes of
9262                    // filtering, because there may be no way for the user to
9263                    // actually re-launch them.
9264                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9265                            && ps.getStopped(userId);
9266                }
9267            }
9268            return false;
9269        }
9270
9271        @Override
9272        protected boolean isPackageForFilter(String packageName,
9273                PackageParser.ProviderIntentInfo info) {
9274            return packageName.equals(info.provider.owner.packageName);
9275        }
9276
9277        @Override
9278        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9279                int match, int userId) {
9280            if (!sUserManager.exists(userId))
9281                return null;
9282            final PackageParser.ProviderIntentInfo info = filter;
9283            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9284                return null;
9285            }
9286            final PackageParser.Provider provider = info.provider;
9287            if (mSafeMode && (provider.info.applicationInfo.flags
9288                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9289                return null;
9290            }
9291            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9292            if (ps == null) {
9293                return null;
9294            }
9295            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9296                    ps.readUserState(userId), userId);
9297            if (pi == null) {
9298                return null;
9299            }
9300            final ResolveInfo res = new ResolveInfo();
9301            res.providerInfo = pi;
9302            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9303                res.filter = filter;
9304            }
9305            res.priority = info.getPriority();
9306            res.preferredOrder = provider.owner.mPreferredOrder;
9307            res.match = match;
9308            res.isDefault = info.hasDefault;
9309            res.labelRes = info.labelRes;
9310            res.nonLocalizedLabel = info.nonLocalizedLabel;
9311            res.icon = info.icon;
9312            res.system = res.providerInfo.applicationInfo.isSystemApp();
9313            return res;
9314        }
9315
9316        @Override
9317        protected void sortResults(List<ResolveInfo> results) {
9318            Collections.sort(results, mResolvePrioritySorter);
9319        }
9320
9321        @Override
9322        protected void dumpFilter(PrintWriter out, String prefix,
9323                PackageParser.ProviderIntentInfo filter) {
9324            out.print(prefix);
9325            out.print(
9326                    Integer.toHexString(System.identityHashCode(filter.provider)));
9327            out.print(' ');
9328            filter.provider.printComponentShortName(out);
9329            out.print(" filter ");
9330            out.println(Integer.toHexString(System.identityHashCode(filter)));
9331        }
9332
9333        @Override
9334        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9335            return filter.provider;
9336        }
9337
9338        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9339            PackageParser.Provider provider = (PackageParser.Provider)label;
9340            out.print(prefix); out.print(
9341                    Integer.toHexString(System.identityHashCode(provider)));
9342                    out.print(' ');
9343                    provider.printComponentShortName(out);
9344            if (count > 1) {
9345                out.print(" ("); out.print(count); out.print(" filters)");
9346            }
9347            out.println();
9348        }
9349
9350        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9351                = new ArrayMap<ComponentName, PackageParser.Provider>();
9352        private int mFlags;
9353    };
9354
9355    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9356            new Comparator<ResolveInfo>() {
9357        public int compare(ResolveInfo r1, ResolveInfo r2) {
9358            int v1 = r1.priority;
9359            int v2 = r2.priority;
9360            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9361            if (v1 != v2) {
9362                return (v1 > v2) ? -1 : 1;
9363            }
9364            v1 = r1.preferredOrder;
9365            v2 = r2.preferredOrder;
9366            if (v1 != v2) {
9367                return (v1 > v2) ? -1 : 1;
9368            }
9369            if (r1.isDefault != r2.isDefault) {
9370                return r1.isDefault ? -1 : 1;
9371            }
9372            v1 = r1.match;
9373            v2 = r2.match;
9374            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9375            if (v1 != v2) {
9376                return (v1 > v2) ? -1 : 1;
9377            }
9378            if (r1.system != r2.system) {
9379                return r1.system ? -1 : 1;
9380            }
9381            return 0;
9382        }
9383    };
9384
9385    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9386            new Comparator<ProviderInfo>() {
9387        public int compare(ProviderInfo p1, ProviderInfo p2) {
9388            final int v1 = p1.initOrder;
9389            final int v2 = p2.initOrder;
9390            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9391        }
9392    };
9393
9394    final void sendPackageBroadcast(final String action, final String pkg,
9395            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9396            final int[] userIds) {
9397        mHandler.post(new Runnable() {
9398            @Override
9399            public void run() {
9400                try {
9401                    final IActivityManager am = ActivityManagerNative.getDefault();
9402                    if (am == null) return;
9403                    final int[] resolvedUserIds;
9404                    if (userIds == null) {
9405                        resolvedUserIds = am.getRunningUserIds();
9406                    } else {
9407                        resolvedUserIds = userIds;
9408                    }
9409                    for (int id : resolvedUserIds) {
9410                        final Intent intent = new Intent(action,
9411                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9412                        if (extras != null) {
9413                            intent.putExtras(extras);
9414                        }
9415                        if (targetPkg != null) {
9416                            intent.setPackage(targetPkg);
9417                        }
9418                        // Modify the UID when posting to other users
9419                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9420                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9421                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9422                            intent.putExtra(Intent.EXTRA_UID, uid);
9423                        }
9424                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9425                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9426                        if (DEBUG_BROADCASTS) {
9427                            RuntimeException here = new RuntimeException("here");
9428                            here.fillInStackTrace();
9429                            Slog.d(TAG, "Sending to user " + id + ": "
9430                                    + intent.toShortString(false, true, false, false)
9431                                    + " " + intent.getExtras(), here);
9432                        }
9433                        am.broadcastIntent(null, intent, null, finishedReceiver,
9434                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9435                                null, finishedReceiver != null, false, id);
9436                    }
9437                } catch (RemoteException ex) {
9438                }
9439            }
9440        });
9441    }
9442
9443    /**
9444     * Check if the external storage media is available. This is true if there
9445     * is a mounted external storage medium or if the external storage is
9446     * emulated.
9447     */
9448    private boolean isExternalMediaAvailable() {
9449        return mMediaMounted || Environment.isExternalStorageEmulated();
9450    }
9451
9452    @Override
9453    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9454        // writer
9455        synchronized (mPackages) {
9456            if (!isExternalMediaAvailable()) {
9457                // If the external storage is no longer mounted at this point,
9458                // the caller may not have been able to delete all of this
9459                // packages files and can not delete any more.  Bail.
9460                return null;
9461            }
9462            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9463            if (lastPackage != null) {
9464                pkgs.remove(lastPackage);
9465            }
9466            if (pkgs.size() > 0) {
9467                return pkgs.get(0);
9468            }
9469        }
9470        return null;
9471    }
9472
9473    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9474        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9475                userId, andCode ? 1 : 0, packageName);
9476        if (mSystemReady) {
9477            msg.sendToTarget();
9478        } else {
9479            if (mPostSystemReadyMessages == null) {
9480                mPostSystemReadyMessages = new ArrayList<>();
9481            }
9482            mPostSystemReadyMessages.add(msg);
9483        }
9484    }
9485
9486    void startCleaningPackages() {
9487        // reader
9488        synchronized (mPackages) {
9489            if (!isExternalMediaAvailable()) {
9490                return;
9491            }
9492            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9493                return;
9494            }
9495        }
9496        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9497        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9498        IActivityManager am = ActivityManagerNative.getDefault();
9499        if (am != null) {
9500            try {
9501                am.startService(null, intent, null, mContext.getOpPackageName(),
9502                        UserHandle.USER_OWNER);
9503            } catch (RemoteException e) {
9504            }
9505        }
9506    }
9507
9508    @Override
9509    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9510            int installFlags, String installerPackageName, VerificationParams verificationParams,
9511            String packageAbiOverride) {
9512        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9513                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9514    }
9515
9516    @Override
9517    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9518            int installFlags, String installerPackageName, VerificationParams verificationParams,
9519            String packageAbiOverride, int userId) {
9520        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9521
9522        final int callingUid = Binder.getCallingUid();
9523        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9524
9525        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9526            try {
9527                if (observer != null) {
9528                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9529                }
9530            } catch (RemoteException re) {
9531            }
9532            return;
9533        }
9534
9535        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9536            installFlags |= PackageManager.INSTALL_FROM_ADB;
9537
9538        } else {
9539            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9540            // about installerPackageName.
9541
9542            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9543            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9544        }
9545
9546        UserHandle user;
9547        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9548            user = UserHandle.ALL;
9549        } else {
9550            user = new UserHandle(userId);
9551        }
9552
9553        // Only system components can circumvent runtime permissions when installing.
9554        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9555                && mContext.checkCallingOrSelfPermission(Manifest.permission
9556                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9557            throw new SecurityException("You need the "
9558                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9559                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9560        }
9561
9562        verificationParams.setInstallerUid(callingUid);
9563
9564        final File originFile = new File(originPath);
9565        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9566
9567        final Message msg = mHandler.obtainMessage(INIT_COPY);
9568        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9569                null, verificationParams, user, packageAbiOverride, null);
9570        mHandler.sendMessage(msg);
9571    }
9572
9573    void installStage(String packageName, File stagedDir, String stagedCid,
9574            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9575            String installerPackageName, int installerUid, UserHandle user) {
9576        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9577                params.referrerUri, installerUid, null);
9578        verifParams.setInstallerUid(installerUid);
9579
9580        final OriginInfo origin;
9581        if (stagedDir != null) {
9582            origin = OriginInfo.fromStagedFile(stagedDir);
9583        } else {
9584            origin = OriginInfo.fromStagedContainer(stagedCid);
9585        }
9586
9587        final Message msg = mHandler.obtainMessage(INIT_COPY);
9588        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9589                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9590                params.grantedRuntimePermissions);
9591        mHandler.sendMessage(msg);
9592    }
9593
9594    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9595        Bundle extras = new Bundle(1);
9596        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9597
9598        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9599                packageName, extras, null, null, new int[] {userId});
9600        try {
9601            IActivityManager am = ActivityManagerNative.getDefault();
9602            final boolean isSystem =
9603                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9604            if (isSystem && am.isUserRunning(userId, false)) {
9605                // The just-installed/enabled app is bundled on the system, so presumed
9606                // to be able to run automatically without needing an explicit launch.
9607                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9608                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9609                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9610                        .setPackage(packageName);
9611                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9612                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9613            }
9614        } catch (RemoteException e) {
9615            // shouldn't happen
9616            Slog.w(TAG, "Unable to bootstrap installed package", e);
9617        }
9618    }
9619
9620    @Override
9621    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9622            int userId) {
9623        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9624        PackageSetting pkgSetting;
9625        final int uid = Binder.getCallingUid();
9626        enforceCrossUserPermission(uid, userId, true, true,
9627                "setApplicationHiddenSetting for user " + userId);
9628
9629        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9630            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9631            return false;
9632        }
9633
9634        long callingId = Binder.clearCallingIdentity();
9635        try {
9636            boolean sendAdded = false;
9637            boolean sendRemoved = false;
9638            // writer
9639            synchronized (mPackages) {
9640                pkgSetting = mSettings.mPackages.get(packageName);
9641                if (pkgSetting == null) {
9642                    return false;
9643                }
9644                if (pkgSetting.getHidden(userId) != hidden) {
9645                    pkgSetting.setHidden(hidden, userId);
9646                    mSettings.writePackageRestrictionsLPr(userId);
9647                    if (hidden) {
9648                        sendRemoved = true;
9649                    } else {
9650                        sendAdded = true;
9651                    }
9652                }
9653            }
9654            if (sendAdded) {
9655                sendPackageAddedForUser(packageName, pkgSetting, userId);
9656                return true;
9657            }
9658            if (sendRemoved) {
9659                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9660                        "hiding pkg");
9661                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9662                return true;
9663            }
9664        } finally {
9665            Binder.restoreCallingIdentity(callingId);
9666        }
9667        return false;
9668    }
9669
9670    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9671            int userId) {
9672        final PackageRemovedInfo info = new PackageRemovedInfo();
9673        info.removedPackage = packageName;
9674        info.removedUsers = new int[] {userId};
9675        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9676        info.sendBroadcast(false, false, false);
9677    }
9678
9679    /**
9680     * Returns true if application is not found or there was an error. Otherwise it returns
9681     * the hidden state of the package for the given user.
9682     */
9683    @Override
9684    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9686        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9687                false, "getApplicationHidden for user " + userId);
9688        PackageSetting pkgSetting;
9689        long callingId = Binder.clearCallingIdentity();
9690        try {
9691            // writer
9692            synchronized (mPackages) {
9693                pkgSetting = mSettings.mPackages.get(packageName);
9694                if (pkgSetting == null) {
9695                    return true;
9696                }
9697                return pkgSetting.getHidden(userId);
9698            }
9699        } finally {
9700            Binder.restoreCallingIdentity(callingId);
9701        }
9702    }
9703
9704    /**
9705     * @hide
9706     */
9707    @Override
9708    public int installExistingPackageAsUser(String packageName, int userId) {
9709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9710                null);
9711        PackageSetting pkgSetting;
9712        final int uid = Binder.getCallingUid();
9713        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9714                + userId);
9715        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9716            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9717        }
9718
9719        long callingId = Binder.clearCallingIdentity();
9720        try {
9721            boolean sendAdded = false;
9722
9723            // writer
9724            synchronized (mPackages) {
9725                pkgSetting = mSettings.mPackages.get(packageName);
9726                if (pkgSetting == null) {
9727                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9728                }
9729                if (!pkgSetting.getInstalled(userId)) {
9730                    pkgSetting.setInstalled(true, userId);
9731                    pkgSetting.setHidden(false, userId);
9732                    mSettings.writePackageRestrictionsLPr(userId);
9733                    sendAdded = true;
9734                }
9735            }
9736
9737            if (sendAdded) {
9738                sendPackageAddedForUser(packageName, pkgSetting, userId);
9739            }
9740        } finally {
9741            Binder.restoreCallingIdentity(callingId);
9742        }
9743
9744        return PackageManager.INSTALL_SUCCEEDED;
9745    }
9746
9747    boolean isUserRestricted(int userId, String restrictionKey) {
9748        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9749        if (restrictions.getBoolean(restrictionKey, false)) {
9750            Log.w(TAG, "User is restricted: " + restrictionKey);
9751            return true;
9752        }
9753        return false;
9754    }
9755
9756    @Override
9757    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9758        mContext.enforceCallingOrSelfPermission(
9759                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9760                "Only package verification agents can verify applications");
9761
9762        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9763        final PackageVerificationResponse response = new PackageVerificationResponse(
9764                verificationCode, Binder.getCallingUid());
9765        msg.arg1 = id;
9766        msg.obj = response;
9767        mHandler.sendMessage(msg);
9768    }
9769
9770    @Override
9771    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9772            long millisecondsToDelay) {
9773        mContext.enforceCallingOrSelfPermission(
9774                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9775                "Only package verification agents can extend verification timeouts");
9776
9777        final PackageVerificationState state = mPendingVerification.get(id);
9778        final PackageVerificationResponse response = new PackageVerificationResponse(
9779                verificationCodeAtTimeout, Binder.getCallingUid());
9780
9781        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9782            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9783        }
9784        if (millisecondsToDelay < 0) {
9785            millisecondsToDelay = 0;
9786        }
9787        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9788                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9789            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9790        }
9791
9792        if ((state != null) && !state.timeoutExtended()) {
9793            state.extendTimeout();
9794
9795            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9796            msg.arg1 = id;
9797            msg.obj = response;
9798            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9799        }
9800    }
9801
9802    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9803            int verificationCode, UserHandle user) {
9804        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9805        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9806        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9807        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9808        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9809
9810        mContext.sendBroadcastAsUser(intent, user,
9811                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9812    }
9813
9814    private ComponentName matchComponentForVerifier(String packageName,
9815            List<ResolveInfo> receivers) {
9816        ActivityInfo targetReceiver = null;
9817
9818        final int NR = receivers.size();
9819        for (int i = 0; i < NR; i++) {
9820            final ResolveInfo info = receivers.get(i);
9821            if (info.activityInfo == null) {
9822                continue;
9823            }
9824
9825            if (packageName.equals(info.activityInfo.packageName)) {
9826                targetReceiver = info.activityInfo;
9827                break;
9828            }
9829        }
9830
9831        if (targetReceiver == null) {
9832            return null;
9833        }
9834
9835        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9836    }
9837
9838    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9839            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9840        if (pkgInfo.verifiers.length == 0) {
9841            return null;
9842        }
9843
9844        final int N = pkgInfo.verifiers.length;
9845        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9846        for (int i = 0; i < N; i++) {
9847            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9848
9849            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9850                    receivers);
9851            if (comp == null) {
9852                continue;
9853            }
9854
9855            final int verifierUid = getUidForVerifier(verifierInfo);
9856            if (verifierUid == -1) {
9857                continue;
9858            }
9859
9860            if (DEBUG_VERIFY) {
9861                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9862                        + " with the correct signature");
9863            }
9864            sufficientVerifiers.add(comp);
9865            verificationState.addSufficientVerifier(verifierUid);
9866        }
9867
9868        return sufficientVerifiers;
9869    }
9870
9871    private int getUidForVerifier(VerifierInfo verifierInfo) {
9872        synchronized (mPackages) {
9873            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9874            if (pkg == null) {
9875                return -1;
9876            } else if (pkg.mSignatures.length != 1) {
9877                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9878                        + " has more than one signature; ignoring");
9879                return -1;
9880            }
9881
9882            /*
9883             * If the public key of the package's signature does not match
9884             * our expected public key, then this is a different package and
9885             * we should skip.
9886             */
9887
9888            final byte[] expectedPublicKey;
9889            try {
9890                final Signature verifierSig = pkg.mSignatures[0];
9891                final PublicKey publicKey = verifierSig.getPublicKey();
9892                expectedPublicKey = publicKey.getEncoded();
9893            } catch (CertificateException e) {
9894                return -1;
9895            }
9896
9897            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9898
9899            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9900                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9901                        + " does not have the expected public key; ignoring");
9902                return -1;
9903            }
9904
9905            return pkg.applicationInfo.uid;
9906        }
9907    }
9908
9909    @Override
9910    public void finishPackageInstall(int token) {
9911        enforceSystemOrRoot("Only the system is allowed to finish installs");
9912
9913        if (DEBUG_INSTALL) {
9914            Slog.v(TAG, "BM finishing package install for " + token);
9915        }
9916
9917        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9918        mHandler.sendMessage(msg);
9919    }
9920
9921    /**
9922     * Get the verification agent timeout.
9923     *
9924     * @return verification timeout in milliseconds
9925     */
9926    private long getVerificationTimeout() {
9927        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9928                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9929                DEFAULT_VERIFICATION_TIMEOUT);
9930    }
9931
9932    /**
9933     * Get the default verification agent response code.
9934     *
9935     * @return default verification response code
9936     */
9937    private int getDefaultVerificationResponse() {
9938        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9939                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9940                DEFAULT_VERIFICATION_RESPONSE);
9941    }
9942
9943    /**
9944     * Check whether or not package verification has been enabled.
9945     *
9946     * @return true if verification should be performed
9947     */
9948    private boolean isVerificationEnabled(int userId, int installFlags) {
9949        if (!DEFAULT_VERIFY_ENABLE) {
9950            return false;
9951        }
9952
9953        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9954
9955        // Check if installing from ADB
9956        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9957            // Do not run verification in a test harness environment
9958            if (ActivityManager.isRunningInTestHarness()) {
9959                return false;
9960            }
9961            if (ensureVerifyAppsEnabled) {
9962                return true;
9963            }
9964            // Check if the developer does not want package verification for ADB installs
9965            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9966                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9967                return false;
9968            }
9969        }
9970
9971        if (ensureVerifyAppsEnabled) {
9972            return true;
9973        }
9974
9975        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9976                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9977    }
9978
9979    @Override
9980    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9981            throws RemoteException {
9982        mContext.enforceCallingOrSelfPermission(
9983                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9984                "Only intentfilter verification agents can verify applications");
9985
9986        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9987        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9988                Binder.getCallingUid(), verificationCode, failedDomains);
9989        msg.arg1 = id;
9990        msg.obj = response;
9991        mHandler.sendMessage(msg);
9992    }
9993
9994    @Override
9995    public int getIntentVerificationStatus(String packageName, int userId) {
9996        synchronized (mPackages) {
9997            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9998        }
9999    }
10000
10001    @Override
10002    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10003        mContext.enforceCallingOrSelfPermission(
10004                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10005
10006        boolean result = false;
10007        synchronized (mPackages) {
10008            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10009        }
10010        if (result) {
10011            scheduleWritePackageRestrictionsLocked(userId);
10012        }
10013        return result;
10014    }
10015
10016    @Override
10017    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10018        synchronized (mPackages) {
10019            return mSettings.getIntentFilterVerificationsLPr(packageName);
10020        }
10021    }
10022
10023    @Override
10024    public List<IntentFilter> getAllIntentFilters(String packageName) {
10025        if (TextUtils.isEmpty(packageName)) {
10026            return Collections.<IntentFilter>emptyList();
10027        }
10028        synchronized (mPackages) {
10029            PackageParser.Package pkg = mPackages.get(packageName);
10030            if (pkg == null || pkg.activities == null) {
10031                return Collections.<IntentFilter>emptyList();
10032            }
10033            final int count = pkg.activities.size();
10034            ArrayList<IntentFilter> result = new ArrayList<>();
10035            for (int n=0; n<count; n++) {
10036                PackageParser.Activity activity = pkg.activities.get(n);
10037                if (activity.intents != null || activity.intents.size() > 0) {
10038                    result.addAll(activity.intents);
10039                }
10040            }
10041            return result;
10042        }
10043    }
10044
10045    @Override
10046    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10047        mContext.enforceCallingOrSelfPermission(
10048                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10049
10050        synchronized (mPackages) {
10051            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10052            if (packageName != null) {
10053                result |= updateIntentVerificationStatus(packageName,
10054                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10055                        userId);
10056                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10057                        packageName, userId);
10058            }
10059            return result;
10060        }
10061    }
10062
10063    @Override
10064    public String getDefaultBrowserPackageName(int userId) {
10065        synchronized (mPackages) {
10066            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10067        }
10068    }
10069
10070    /**
10071     * Get the "allow unknown sources" setting.
10072     *
10073     * @return the current "allow unknown sources" setting
10074     */
10075    private int getUnknownSourcesSettings() {
10076        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10077                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10078                -1);
10079    }
10080
10081    @Override
10082    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10083        final int uid = Binder.getCallingUid();
10084        // writer
10085        synchronized (mPackages) {
10086            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10087            if (targetPackageSetting == null) {
10088                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10089            }
10090
10091            PackageSetting installerPackageSetting;
10092            if (installerPackageName != null) {
10093                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10094                if (installerPackageSetting == null) {
10095                    throw new IllegalArgumentException("Unknown installer package: "
10096                            + installerPackageName);
10097                }
10098            } else {
10099                installerPackageSetting = null;
10100            }
10101
10102            Signature[] callerSignature;
10103            Object obj = mSettings.getUserIdLPr(uid);
10104            if (obj != null) {
10105                if (obj instanceof SharedUserSetting) {
10106                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10107                } else if (obj instanceof PackageSetting) {
10108                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10109                } else {
10110                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10111                }
10112            } else {
10113                throw new SecurityException("Unknown calling uid " + uid);
10114            }
10115
10116            // Verify: can't set installerPackageName to a package that is
10117            // not signed with the same cert as the caller.
10118            if (installerPackageSetting != null) {
10119                if (compareSignatures(callerSignature,
10120                        installerPackageSetting.signatures.mSignatures)
10121                        != PackageManager.SIGNATURE_MATCH) {
10122                    throw new SecurityException(
10123                            "Caller does not have same cert as new installer package "
10124                            + installerPackageName);
10125                }
10126            }
10127
10128            // Verify: if target already has an installer package, it must
10129            // be signed with the same cert as the caller.
10130            if (targetPackageSetting.installerPackageName != null) {
10131                PackageSetting setting = mSettings.mPackages.get(
10132                        targetPackageSetting.installerPackageName);
10133                // If the currently set package isn't valid, then it's always
10134                // okay to change it.
10135                if (setting != null) {
10136                    if (compareSignatures(callerSignature,
10137                            setting.signatures.mSignatures)
10138                            != PackageManager.SIGNATURE_MATCH) {
10139                        throw new SecurityException(
10140                                "Caller does not have same cert as old installer package "
10141                                + targetPackageSetting.installerPackageName);
10142                    }
10143                }
10144            }
10145
10146            // Okay!
10147            targetPackageSetting.installerPackageName = installerPackageName;
10148            scheduleWriteSettingsLocked();
10149        }
10150    }
10151
10152    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10153        // Queue up an async operation since the package installation may take a little while.
10154        mHandler.post(new Runnable() {
10155            public void run() {
10156                mHandler.removeCallbacks(this);
10157                 // Result object to be returned
10158                PackageInstalledInfo res = new PackageInstalledInfo();
10159                res.returnCode = currentStatus;
10160                res.uid = -1;
10161                res.pkg = null;
10162                res.removedInfo = new PackageRemovedInfo();
10163                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10164                    args.doPreInstall(res.returnCode);
10165                    synchronized (mInstallLock) {
10166                        installPackageLI(args, res);
10167                    }
10168                    args.doPostInstall(res.returnCode, res.uid);
10169                }
10170
10171                // A restore should be performed at this point if (a) the install
10172                // succeeded, (b) the operation is not an update, and (c) the new
10173                // package has not opted out of backup participation.
10174                final boolean update = res.removedInfo.removedPackage != null;
10175                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10176                boolean doRestore = !update
10177                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10178
10179                // Set up the post-install work request bookkeeping.  This will be used
10180                // and cleaned up by the post-install event handling regardless of whether
10181                // there's a restore pass performed.  Token values are >= 1.
10182                int token;
10183                if (mNextInstallToken < 0) mNextInstallToken = 1;
10184                token = mNextInstallToken++;
10185
10186                PostInstallData data = new PostInstallData(args, res);
10187                mRunningInstalls.put(token, data);
10188                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10189
10190                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10191                    // Pass responsibility to the Backup Manager.  It will perform a
10192                    // restore if appropriate, then pass responsibility back to the
10193                    // Package Manager to run the post-install observer callbacks
10194                    // and broadcasts.
10195                    IBackupManager bm = IBackupManager.Stub.asInterface(
10196                            ServiceManager.getService(Context.BACKUP_SERVICE));
10197                    if (bm != null) {
10198                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10199                                + " to BM for possible restore");
10200                        try {
10201                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10202                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10203                            } else {
10204                                doRestore = false;
10205                            }
10206                        } catch (RemoteException e) {
10207                            // can't happen; the backup manager is local
10208                        } catch (Exception e) {
10209                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10210                            doRestore = false;
10211                        }
10212                    } else {
10213                        Slog.e(TAG, "Backup Manager not found!");
10214                        doRestore = false;
10215                    }
10216                }
10217
10218                if (!doRestore) {
10219                    // No restore possible, or the Backup Manager was mysteriously not
10220                    // available -- just fire the post-install work request directly.
10221                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10222                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10223                    mHandler.sendMessage(msg);
10224                }
10225            }
10226        });
10227    }
10228
10229    private abstract class HandlerParams {
10230        private static final int MAX_RETRIES = 4;
10231
10232        /**
10233         * Number of times startCopy() has been attempted and had a non-fatal
10234         * error.
10235         */
10236        private int mRetries = 0;
10237
10238        /** User handle for the user requesting the information or installation. */
10239        private final UserHandle mUser;
10240
10241        HandlerParams(UserHandle user) {
10242            mUser = user;
10243        }
10244
10245        UserHandle getUser() {
10246            return mUser;
10247        }
10248
10249        final boolean startCopy() {
10250            boolean res;
10251            try {
10252                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10253
10254                if (++mRetries > MAX_RETRIES) {
10255                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10256                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10257                    handleServiceError();
10258                    return false;
10259                } else {
10260                    handleStartCopy();
10261                    res = true;
10262                }
10263            } catch (RemoteException e) {
10264                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10265                mHandler.sendEmptyMessage(MCS_RECONNECT);
10266                res = false;
10267            }
10268            handleReturnCode();
10269            return res;
10270        }
10271
10272        final void serviceError() {
10273            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10274            handleServiceError();
10275            handleReturnCode();
10276        }
10277
10278        abstract void handleStartCopy() throws RemoteException;
10279        abstract void handleServiceError();
10280        abstract void handleReturnCode();
10281    }
10282
10283    class MeasureParams extends HandlerParams {
10284        private final PackageStats mStats;
10285        private boolean mSuccess;
10286
10287        private final IPackageStatsObserver mObserver;
10288
10289        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10290            super(new UserHandle(stats.userHandle));
10291            mObserver = observer;
10292            mStats = stats;
10293        }
10294
10295        @Override
10296        public String toString() {
10297            return "MeasureParams{"
10298                + Integer.toHexString(System.identityHashCode(this))
10299                + " " + mStats.packageName + "}";
10300        }
10301
10302        @Override
10303        void handleStartCopy() throws RemoteException {
10304            synchronized (mInstallLock) {
10305                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10306            }
10307
10308            if (mSuccess) {
10309                final boolean mounted;
10310                if (Environment.isExternalStorageEmulated()) {
10311                    mounted = true;
10312                } else {
10313                    final String status = Environment.getExternalStorageState();
10314                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10315                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10316                }
10317
10318                if (mounted) {
10319                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10320
10321                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10322                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10323
10324                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10325                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10326
10327                    // Always subtract cache size, since it's a subdirectory
10328                    mStats.externalDataSize -= mStats.externalCacheSize;
10329
10330                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10331                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10332
10333                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10334                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10335                }
10336            }
10337        }
10338
10339        @Override
10340        void handleReturnCode() {
10341            if (mObserver != null) {
10342                try {
10343                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10344                } catch (RemoteException e) {
10345                    Slog.i(TAG, "Observer no longer exists.");
10346                }
10347            }
10348        }
10349
10350        @Override
10351        void handleServiceError() {
10352            Slog.e(TAG, "Could not measure application " + mStats.packageName
10353                            + " external storage");
10354        }
10355    }
10356
10357    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10358            throws RemoteException {
10359        long result = 0;
10360        for (File path : paths) {
10361            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10362        }
10363        return result;
10364    }
10365
10366    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10367        for (File path : paths) {
10368            try {
10369                mcs.clearDirectory(path.getAbsolutePath());
10370            } catch (RemoteException e) {
10371            }
10372        }
10373    }
10374
10375    static class OriginInfo {
10376        /**
10377         * Location where install is coming from, before it has been
10378         * copied/renamed into place. This could be a single monolithic APK
10379         * file, or a cluster directory. This location may be untrusted.
10380         */
10381        final File file;
10382        final String cid;
10383
10384        /**
10385         * Flag indicating that {@link #file} or {@link #cid} has already been
10386         * staged, meaning downstream users don't need to defensively copy the
10387         * contents.
10388         */
10389        final boolean staged;
10390
10391        /**
10392         * Flag indicating that {@link #file} or {@link #cid} is an already
10393         * installed app that is being moved.
10394         */
10395        final boolean existing;
10396
10397        final String resolvedPath;
10398        final File resolvedFile;
10399
10400        static OriginInfo fromNothing() {
10401            return new OriginInfo(null, null, false, false);
10402        }
10403
10404        static OriginInfo fromUntrustedFile(File file) {
10405            return new OriginInfo(file, null, false, false);
10406        }
10407
10408        static OriginInfo fromExistingFile(File file) {
10409            return new OriginInfo(file, null, false, true);
10410        }
10411
10412        static OriginInfo fromStagedFile(File file) {
10413            return new OriginInfo(file, null, true, false);
10414        }
10415
10416        static OriginInfo fromStagedContainer(String cid) {
10417            return new OriginInfo(null, cid, true, false);
10418        }
10419
10420        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10421            this.file = file;
10422            this.cid = cid;
10423            this.staged = staged;
10424            this.existing = existing;
10425
10426            if (cid != null) {
10427                resolvedPath = PackageHelper.getSdDir(cid);
10428                resolvedFile = new File(resolvedPath);
10429            } else if (file != null) {
10430                resolvedPath = file.getAbsolutePath();
10431                resolvedFile = file;
10432            } else {
10433                resolvedPath = null;
10434                resolvedFile = null;
10435            }
10436        }
10437    }
10438
10439    class MoveInfo {
10440        final int moveId;
10441        final String fromUuid;
10442        final String toUuid;
10443        final String packageName;
10444        final String dataAppName;
10445        final int appId;
10446        final String seinfo;
10447
10448        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10449                String dataAppName, int appId, String seinfo) {
10450            this.moveId = moveId;
10451            this.fromUuid = fromUuid;
10452            this.toUuid = toUuid;
10453            this.packageName = packageName;
10454            this.dataAppName = dataAppName;
10455            this.appId = appId;
10456            this.seinfo = seinfo;
10457        }
10458    }
10459
10460    class InstallParams extends HandlerParams {
10461        final OriginInfo origin;
10462        final MoveInfo move;
10463        final IPackageInstallObserver2 observer;
10464        int installFlags;
10465        final String installerPackageName;
10466        final String volumeUuid;
10467        final VerificationParams verificationParams;
10468        private InstallArgs mArgs;
10469        private int mRet;
10470        final String packageAbiOverride;
10471        final String[] grantedRuntimePermissions;
10472
10473
10474        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10475                int installFlags, String installerPackageName, String volumeUuid,
10476                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10477                String[] grantedPermissions) {
10478            super(user);
10479            this.origin = origin;
10480            this.move = move;
10481            this.observer = observer;
10482            this.installFlags = installFlags;
10483            this.installerPackageName = installerPackageName;
10484            this.volumeUuid = volumeUuid;
10485            this.verificationParams = verificationParams;
10486            this.packageAbiOverride = packageAbiOverride;
10487            this.grantedRuntimePermissions = grantedPermissions;
10488        }
10489
10490        @Override
10491        public String toString() {
10492            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10493                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10494        }
10495
10496        public ManifestDigest getManifestDigest() {
10497            if (verificationParams == null) {
10498                return null;
10499            }
10500            return verificationParams.getManifestDigest();
10501        }
10502
10503        private int installLocationPolicy(PackageInfoLite pkgLite) {
10504            String packageName = pkgLite.packageName;
10505            int installLocation = pkgLite.installLocation;
10506            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10507            // reader
10508            synchronized (mPackages) {
10509                PackageParser.Package pkg = mPackages.get(packageName);
10510                if (pkg != null) {
10511                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10512                        // Check for downgrading.
10513                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10514                            try {
10515                                checkDowngrade(pkg, pkgLite);
10516                            } catch (PackageManagerException e) {
10517                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10518                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10519                            }
10520                        }
10521                        // Check for updated system application.
10522                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10523                            if (onSd) {
10524                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10525                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10526                            }
10527                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10528                        } else {
10529                            if (onSd) {
10530                                // Install flag overrides everything.
10531                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10532                            }
10533                            // If current upgrade specifies particular preference
10534                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10535                                // Application explicitly specified internal.
10536                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10537                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10538                                // App explictly prefers external. Let policy decide
10539                            } else {
10540                                // Prefer previous location
10541                                if (isExternal(pkg)) {
10542                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10543                                }
10544                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10545                            }
10546                        }
10547                    } else {
10548                        // Invalid install. Return error code
10549                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10550                    }
10551                }
10552            }
10553            // All the special cases have been taken care of.
10554            // Return result based on recommended install location.
10555            if (onSd) {
10556                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10557            }
10558            return pkgLite.recommendedInstallLocation;
10559        }
10560
10561        /*
10562         * Invoke remote method to get package information and install
10563         * location values. Override install location based on default
10564         * policy if needed and then create install arguments based
10565         * on the install location.
10566         */
10567        public void handleStartCopy() throws RemoteException {
10568            int ret = PackageManager.INSTALL_SUCCEEDED;
10569
10570            // If we're already staged, we've firmly committed to an install location
10571            if (origin.staged) {
10572                if (origin.file != null) {
10573                    installFlags |= PackageManager.INSTALL_INTERNAL;
10574                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10575                } else if (origin.cid != null) {
10576                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10577                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10578                } else {
10579                    throw new IllegalStateException("Invalid stage location");
10580                }
10581            }
10582
10583            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10584            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10585
10586            PackageInfoLite pkgLite = null;
10587
10588            if (onInt && onSd) {
10589                // Check if both bits are set.
10590                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10591                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10592            } else {
10593                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10594                        packageAbiOverride);
10595
10596                /*
10597                 * If we have too little free space, try to free cache
10598                 * before giving up.
10599                 */
10600                if (!origin.staged && pkgLite.recommendedInstallLocation
10601                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10602                    // TODO: focus freeing disk space on the target device
10603                    final StorageManager storage = StorageManager.from(mContext);
10604                    final long lowThreshold = storage.getStorageLowBytes(
10605                            Environment.getDataDirectory());
10606
10607                    final long sizeBytes = mContainerService.calculateInstalledSize(
10608                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10609
10610                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10611                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10612                                installFlags, packageAbiOverride);
10613                    }
10614
10615                    /*
10616                     * The cache free must have deleted the file we
10617                     * downloaded to install.
10618                     *
10619                     * TODO: fix the "freeCache" call to not delete
10620                     *       the file we care about.
10621                     */
10622                    if (pkgLite.recommendedInstallLocation
10623                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10624                        pkgLite.recommendedInstallLocation
10625                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10626                    }
10627                }
10628            }
10629
10630            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10631                int loc = pkgLite.recommendedInstallLocation;
10632                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10633                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10634                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10635                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10636                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10637                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10638                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10639                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10640                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10641                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10642                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10643                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10644                } else {
10645                    // Override with defaults if needed.
10646                    loc = installLocationPolicy(pkgLite);
10647                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10648                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10649                    } else if (!onSd && !onInt) {
10650                        // Override install location with flags
10651                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10652                            // Set the flag to install on external media.
10653                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10654                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10655                        } else {
10656                            // Make sure the flag for installing on external
10657                            // media is unset
10658                            installFlags |= PackageManager.INSTALL_INTERNAL;
10659                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10660                        }
10661                    }
10662                }
10663            }
10664
10665            final InstallArgs args = createInstallArgs(this);
10666            mArgs = args;
10667
10668            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10669                 /*
10670                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10671                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10672                 */
10673                int userIdentifier = getUser().getIdentifier();
10674                if (userIdentifier == UserHandle.USER_ALL
10675                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10676                    userIdentifier = UserHandle.USER_OWNER;
10677                }
10678
10679                /*
10680                 * Determine if we have any installed package verifiers. If we
10681                 * do, then we'll defer to them to verify the packages.
10682                 */
10683                final int requiredUid = mRequiredVerifierPackage == null ? -1
10684                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10685                if (!origin.existing && requiredUid != -1
10686                        && isVerificationEnabled(userIdentifier, installFlags)) {
10687                    final Intent verification = new Intent(
10688                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10689                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10690                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10691                            PACKAGE_MIME_TYPE);
10692                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10693
10694                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10695                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10696                            0 /* TODO: Which userId? */);
10697
10698                    if (DEBUG_VERIFY) {
10699                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10700                                + verification.toString() + " with " + pkgLite.verifiers.length
10701                                + " optional verifiers");
10702                    }
10703
10704                    final int verificationId = mPendingVerificationToken++;
10705
10706                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10707
10708                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10709                            installerPackageName);
10710
10711                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10712                            installFlags);
10713
10714                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10715                            pkgLite.packageName);
10716
10717                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10718                            pkgLite.versionCode);
10719
10720                    if (verificationParams != null) {
10721                        if (verificationParams.getVerificationURI() != null) {
10722                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10723                                 verificationParams.getVerificationURI());
10724                        }
10725                        if (verificationParams.getOriginatingURI() != null) {
10726                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10727                                  verificationParams.getOriginatingURI());
10728                        }
10729                        if (verificationParams.getReferrer() != null) {
10730                            verification.putExtra(Intent.EXTRA_REFERRER,
10731                                  verificationParams.getReferrer());
10732                        }
10733                        if (verificationParams.getOriginatingUid() >= 0) {
10734                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10735                                  verificationParams.getOriginatingUid());
10736                        }
10737                        if (verificationParams.getInstallerUid() >= 0) {
10738                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10739                                  verificationParams.getInstallerUid());
10740                        }
10741                    }
10742
10743                    final PackageVerificationState verificationState = new PackageVerificationState(
10744                            requiredUid, args);
10745
10746                    mPendingVerification.append(verificationId, verificationState);
10747
10748                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10749                            receivers, verificationState);
10750
10751                    // Apps installed for "all" users use the device owner to verify the app
10752                    UserHandle verifierUser = getUser();
10753                    if (verifierUser == UserHandle.ALL) {
10754                        verifierUser = UserHandle.OWNER;
10755                    }
10756
10757                    /*
10758                     * If any sufficient verifiers were listed in the package
10759                     * manifest, attempt to ask them.
10760                     */
10761                    if (sufficientVerifiers != null) {
10762                        final int N = sufficientVerifiers.size();
10763                        if (N == 0) {
10764                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10765                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10766                        } else {
10767                            for (int i = 0; i < N; i++) {
10768                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10769
10770                                final Intent sufficientIntent = new Intent(verification);
10771                                sufficientIntent.setComponent(verifierComponent);
10772                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10773                            }
10774                        }
10775                    }
10776
10777                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10778                            mRequiredVerifierPackage, receivers);
10779                    if (ret == PackageManager.INSTALL_SUCCEEDED
10780                            && mRequiredVerifierPackage != null) {
10781                        /*
10782                         * Send the intent to the required verification agent,
10783                         * but only start the verification timeout after the
10784                         * target BroadcastReceivers have run.
10785                         */
10786                        verification.setComponent(requiredVerifierComponent);
10787                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10788                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10789                                new BroadcastReceiver() {
10790                                    @Override
10791                                    public void onReceive(Context context, Intent intent) {
10792                                        final Message msg = mHandler
10793                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10794                                        msg.arg1 = verificationId;
10795                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10796                                    }
10797                                }, null, 0, null, null);
10798
10799                        /*
10800                         * We don't want the copy to proceed until verification
10801                         * succeeds, so null out this field.
10802                         */
10803                        mArgs = null;
10804                    }
10805                } else {
10806                    /*
10807                     * No package verification is enabled, so immediately start
10808                     * the remote call to initiate copy using temporary file.
10809                     */
10810                    ret = args.copyApk(mContainerService, true);
10811                }
10812            }
10813
10814            mRet = ret;
10815        }
10816
10817        @Override
10818        void handleReturnCode() {
10819            // If mArgs is null, then MCS couldn't be reached. When it
10820            // reconnects, it will try again to install. At that point, this
10821            // will succeed.
10822            if (mArgs != null) {
10823                processPendingInstall(mArgs, mRet);
10824            }
10825        }
10826
10827        @Override
10828        void handleServiceError() {
10829            mArgs = createInstallArgs(this);
10830            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10831        }
10832
10833        public boolean isForwardLocked() {
10834            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10835        }
10836    }
10837
10838    /**
10839     * Used during creation of InstallArgs
10840     *
10841     * @param installFlags package installation flags
10842     * @return true if should be installed on external storage
10843     */
10844    private static boolean installOnExternalAsec(int installFlags) {
10845        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10846            return false;
10847        }
10848        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10849            return true;
10850        }
10851        return false;
10852    }
10853
10854    /**
10855     * Used during creation of InstallArgs
10856     *
10857     * @param installFlags package installation flags
10858     * @return true if should be installed as forward locked
10859     */
10860    private static boolean installForwardLocked(int installFlags) {
10861        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10862    }
10863
10864    private InstallArgs createInstallArgs(InstallParams params) {
10865        if (params.move != null) {
10866            return new MoveInstallArgs(params);
10867        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10868            return new AsecInstallArgs(params);
10869        } else {
10870            return new FileInstallArgs(params);
10871        }
10872    }
10873
10874    /**
10875     * Create args that describe an existing installed package. Typically used
10876     * when cleaning up old installs, or used as a move source.
10877     */
10878    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10879            String resourcePath, String[] instructionSets) {
10880        final boolean isInAsec;
10881        if (installOnExternalAsec(installFlags)) {
10882            /* Apps on SD card are always in ASEC containers. */
10883            isInAsec = true;
10884        } else if (installForwardLocked(installFlags)
10885                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10886            /*
10887             * Forward-locked apps are only in ASEC containers if they're the
10888             * new style
10889             */
10890            isInAsec = true;
10891        } else {
10892            isInAsec = false;
10893        }
10894
10895        if (isInAsec) {
10896            return new AsecInstallArgs(codePath, instructionSets,
10897                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10898        } else {
10899            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10900        }
10901    }
10902
10903    static abstract class InstallArgs {
10904        /** @see InstallParams#origin */
10905        final OriginInfo origin;
10906        /** @see InstallParams#move */
10907        final MoveInfo move;
10908
10909        final IPackageInstallObserver2 observer;
10910        // Always refers to PackageManager flags only
10911        final int installFlags;
10912        final String installerPackageName;
10913        final String volumeUuid;
10914        final ManifestDigest manifestDigest;
10915        final UserHandle user;
10916        final String abiOverride;
10917        final String[] installGrantPermissions;
10918
10919        // The list of instruction sets supported by this app. This is currently
10920        // only used during the rmdex() phase to clean up resources. We can get rid of this
10921        // if we move dex files under the common app path.
10922        /* nullable */ String[] instructionSets;
10923
10924        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10925                int installFlags, String installerPackageName, String volumeUuid,
10926                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10927                String abiOverride, String[] installGrantPermissions) {
10928            this.origin = origin;
10929            this.move = move;
10930            this.installFlags = installFlags;
10931            this.observer = observer;
10932            this.installerPackageName = installerPackageName;
10933            this.volumeUuid = volumeUuid;
10934            this.manifestDigest = manifestDigest;
10935            this.user = user;
10936            this.instructionSets = instructionSets;
10937            this.abiOverride = abiOverride;
10938            this.installGrantPermissions = installGrantPermissions;
10939        }
10940
10941        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10942        abstract int doPreInstall(int status);
10943
10944        /**
10945         * Rename package into final resting place. All paths on the given
10946         * scanned package should be updated to reflect the rename.
10947         */
10948        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10949        abstract int doPostInstall(int status, int uid);
10950
10951        /** @see PackageSettingBase#codePathString */
10952        abstract String getCodePath();
10953        /** @see PackageSettingBase#resourcePathString */
10954        abstract String getResourcePath();
10955
10956        // Need installer lock especially for dex file removal.
10957        abstract void cleanUpResourcesLI();
10958        abstract boolean doPostDeleteLI(boolean delete);
10959
10960        /**
10961         * Called before the source arguments are copied. This is used mostly
10962         * for MoveParams when it needs to read the source file to put it in the
10963         * destination.
10964         */
10965        int doPreCopy() {
10966            return PackageManager.INSTALL_SUCCEEDED;
10967        }
10968
10969        /**
10970         * Called after the source arguments are copied. This is used mostly for
10971         * MoveParams when it needs to read the source file to put it in the
10972         * destination.
10973         *
10974         * @return
10975         */
10976        int doPostCopy(int uid) {
10977            return PackageManager.INSTALL_SUCCEEDED;
10978        }
10979
10980        protected boolean isFwdLocked() {
10981            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10982        }
10983
10984        protected boolean isExternalAsec() {
10985            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10986        }
10987
10988        UserHandle getUser() {
10989            return user;
10990        }
10991    }
10992
10993    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10994        if (!allCodePaths.isEmpty()) {
10995            if (instructionSets == null) {
10996                throw new IllegalStateException("instructionSet == null");
10997            }
10998            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10999            for (String codePath : allCodePaths) {
11000                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11001                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11002                    if (retCode < 0) {
11003                        Slog.w(TAG, "Couldn't remove dex file for package: "
11004                                + " at location " + codePath + ", retcode=" + retCode);
11005                        // we don't consider this to be a failure of the core package deletion
11006                    }
11007                }
11008            }
11009        }
11010    }
11011
11012    /**
11013     * Logic to handle installation of non-ASEC applications, including copying
11014     * and renaming logic.
11015     */
11016    class FileInstallArgs extends InstallArgs {
11017        private File codeFile;
11018        private File resourceFile;
11019
11020        // Example topology:
11021        // /data/app/com.example/base.apk
11022        // /data/app/com.example/split_foo.apk
11023        // /data/app/com.example/lib/arm/libfoo.so
11024        // /data/app/com.example/lib/arm64/libfoo.so
11025        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11026
11027        /** New install */
11028        FileInstallArgs(InstallParams params) {
11029            super(params.origin, params.move, params.observer, params.installFlags,
11030                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11031                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11032                    params.grantedRuntimePermissions);
11033            if (isFwdLocked()) {
11034                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11035            }
11036        }
11037
11038        /** Existing install */
11039        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11040            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11041                    null, null);
11042            this.codeFile = (codePath != null) ? new File(codePath) : null;
11043            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11044        }
11045
11046        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11047            if (origin.staged) {
11048                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11049                codeFile = origin.file;
11050                resourceFile = origin.file;
11051                return PackageManager.INSTALL_SUCCEEDED;
11052            }
11053
11054            try {
11055                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11056                codeFile = tempDir;
11057                resourceFile = tempDir;
11058            } catch (IOException e) {
11059                Slog.w(TAG, "Failed to create copy file: " + e);
11060                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11061            }
11062
11063            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11064                @Override
11065                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11066                    if (!FileUtils.isValidExtFilename(name)) {
11067                        throw new IllegalArgumentException("Invalid filename: " + name);
11068                    }
11069                    try {
11070                        final File file = new File(codeFile, name);
11071                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11072                                O_RDWR | O_CREAT, 0644);
11073                        Os.chmod(file.getAbsolutePath(), 0644);
11074                        return new ParcelFileDescriptor(fd);
11075                    } catch (ErrnoException e) {
11076                        throw new RemoteException("Failed to open: " + e.getMessage());
11077                    }
11078                }
11079            };
11080
11081            int ret = PackageManager.INSTALL_SUCCEEDED;
11082            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11083            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11084                Slog.e(TAG, "Failed to copy package");
11085                return ret;
11086            }
11087
11088            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11089            NativeLibraryHelper.Handle handle = null;
11090            try {
11091                handle = NativeLibraryHelper.Handle.create(codeFile);
11092                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11093                        abiOverride);
11094            } catch (IOException e) {
11095                Slog.e(TAG, "Copying native libraries failed", e);
11096                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11097            } finally {
11098                IoUtils.closeQuietly(handle);
11099            }
11100
11101            return ret;
11102        }
11103
11104        int doPreInstall(int status) {
11105            if (status != PackageManager.INSTALL_SUCCEEDED) {
11106                cleanUp();
11107            }
11108            return status;
11109        }
11110
11111        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11112            if (status != PackageManager.INSTALL_SUCCEEDED) {
11113                cleanUp();
11114                return false;
11115            }
11116
11117            final File targetDir = codeFile.getParentFile();
11118            final File beforeCodeFile = codeFile;
11119            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11120
11121            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11122            try {
11123                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11124            } catch (ErrnoException e) {
11125                Slog.w(TAG, "Failed to rename", e);
11126                return false;
11127            }
11128
11129            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11130                Slog.w(TAG, "Failed to restorecon");
11131                return false;
11132            }
11133
11134            // Reflect the rename internally
11135            codeFile = afterCodeFile;
11136            resourceFile = afterCodeFile;
11137
11138            // Reflect the rename in scanned details
11139            pkg.codePath = afterCodeFile.getAbsolutePath();
11140            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11141                    pkg.baseCodePath);
11142            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11143                    pkg.splitCodePaths);
11144
11145            // Reflect the rename in app info
11146            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11147            pkg.applicationInfo.setCodePath(pkg.codePath);
11148            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11149            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11150            pkg.applicationInfo.setResourcePath(pkg.codePath);
11151            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11152            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11153
11154            return true;
11155        }
11156
11157        int doPostInstall(int status, int uid) {
11158            if (status != PackageManager.INSTALL_SUCCEEDED) {
11159                cleanUp();
11160            }
11161            return status;
11162        }
11163
11164        @Override
11165        String getCodePath() {
11166            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11167        }
11168
11169        @Override
11170        String getResourcePath() {
11171            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11172        }
11173
11174        private boolean cleanUp() {
11175            if (codeFile == null || !codeFile.exists()) {
11176                return false;
11177            }
11178
11179            if (codeFile.isDirectory()) {
11180                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11181            } else {
11182                codeFile.delete();
11183            }
11184
11185            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11186                resourceFile.delete();
11187            }
11188
11189            return true;
11190        }
11191
11192        void cleanUpResourcesLI() {
11193            // Try enumerating all code paths before deleting
11194            List<String> allCodePaths = Collections.EMPTY_LIST;
11195            if (codeFile != null && codeFile.exists()) {
11196                try {
11197                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11198                    allCodePaths = pkg.getAllCodePaths();
11199                } catch (PackageParserException e) {
11200                    // Ignored; we tried our best
11201                }
11202            }
11203
11204            cleanUp();
11205            removeDexFiles(allCodePaths, instructionSets);
11206        }
11207
11208        boolean doPostDeleteLI(boolean delete) {
11209            // XXX err, shouldn't we respect the delete flag?
11210            cleanUpResourcesLI();
11211            return true;
11212        }
11213    }
11214
11215    private boolean isAsecExternal(String cid) {
11216        final String asecPath = PackageHelper.getSdFilesystem(cid);
11217        return !asecPath.startsWith(mAsecInternalPath);
11218    }
11219
11220    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11221            PackageManagerException {
11222        if (copyRet < 0) {
11223            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11224                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11225                throw new PackageManagerException(copyRet, message);
11226            }
11227        }
11228    }
11229
11230    /**
11231     * Extract the MountService "container ID" from the full code path of an
11232     * .apk.
11233     */
11234    static String cidFromCodePath(String fullCodePath) {
11235        int eidx = fullCodePath.lastIndexOf("/");
11236        String subStr1 = fullCodePath.substring(0, eidx);
11237        int sidx = subStr1.lastIndexOf("/");
11238        return subStr1.substring(sidx+1, eidx);
11239    }
11240
11241    /**
11242     * Logic to handle installation of ASEC applications, including copying and
11243     * renaming logic.
11244     */
11245    class AsecInstallArgs extends InstallArgs {
11246        static final String RES_FILE_NAME = "pkg.apk";
11247        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11248
11249        String cid;
11250        String packagePath;
11251        String resourcePath;
11252
11253        /** New install */
11254        AsecInstallArgs(InstallParams params) {
11255            super(params.origin, params.move, params.observer, params.installFlags,
11256                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11257                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11258                    params.grantedRuntimePermissions);
11259        }
11260
11261        /** Existing install */
11262        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11263                        boolean isExternal, boolean isForwardLocked) {
11264            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11265                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11266                    instructionSets, null, null);
11267            // Hackily pretend we're still looking at a full code path
11268            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11269                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11270            }
11271
11272            // Extract cid from fullCodePath
11273            int eidx = fullCodePath.lastIndexOf("/");
11274            String subStr1 = fullCodePath.substring(0, eidx);
11275            int sidx = subStr1.lastIndexOf("/");
11276            cid = subStr1.substring(sidx+1, eidx);
11277            setMountPath(subStr1);
11278        }
11279
11280        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11281            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11282                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11283                    instructionSets, null, null);
11284            this.cid = cid;
11285            setMountPath(PackageHelper.getSdDir(cid));
11286        }
11287
11288        void createCopyFile() {
11289            cid = mInstallerService.allocateExternalStageCidLegacy();
11290        }
11291
11292        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11293            if (origin.staged) {
11294                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11295                cid = origin.cid;
11296                setMountPath(PackageHelper.getSdDir(cid));
11297                return PackageManager.INSTALL_SUCCEEDED;
11298            }
11299
11300            if (temp) {
11301                createCopyFile();
11302            } else {
11303                /*
11304                 * Pre-emptively destroy the container since it's destroyed if
11305                 * copying fails due to it existing anyway.
11306                 */
11307                PackageHelper.destroySdDir(cid);
11308            }
11309
11310            final String newMountPath = imcs.copyPackageToContainer(
11311                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11312                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11313
11314            if (newMountPath != null) {
11315                setMountPath(newMountPath);
11316                return PackageManager.INSTALL_SUCCEEDED;
11317            } else {
11318                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11319            }
11320        }
11321
11322        @Override
11323        String getCodePath() {
11324            return packagePath;
11325        }
11326
11327        @Override
11328        String getResourcePath() {
11329            return resourcePath;
11330        }
11331
11332        int doPreInstall(int status) {
11333            if (status != PackageManager.INSTALL_SUCCEEDED) {
11334                // Destroy container
11335                PackageHelper.destroySdDir(cid);
11336            } else {
11337                boolean mounted = PackageHelper.isContainerMounted(cid);
11338                if (!mounted) {
11339                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11340                            Process.SYSTEM_UID);
11341                    if (newMountPath != null) {
11342                        setMountPath(newMountPath);
11343                    } else {
11344                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11345                    }
11346                }
11347            }
11348            return status;
11349        }
11350
11351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11352            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11353            String newMountPath = null;
11354            if (PackageHelper.isContainerMounted(cid)) {
11355                // Unmount the container
11356                if (!PackageHelper.unMountSdDir(cid)) {
11357                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11358                    return false;
11359                }
11360            }
11361            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11362                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11363                        " which might be stale. Will try to clean up.");
11364                // Clean up the stale container and proceed to recreate.
11365                if (!PackageHelper.destroySdDir(newCacheId)) {
11366                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11367                    return false;
11368                }
11369                // Successfully cleaned up stale container. Try to rename again.
11370                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11371                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11372                            + " inspite of cleaning it up.");
11373                    return false;
11374                }
11375            }
11376            if (!PackageHelper.isContainerMounted(newCacheId)) {
11377                Slog.w(TAG, "Mounting container " + newCacheId);
11378                newMountPath = PackageHelper.mountSdDir(newCacheId,
11379                        getEncryptKey(), Process.SYSTEM_UID);
11380            } else {
11381                newMountPath = PackageHelper.getSdDir(newCacheId);
11382            }
11383            if (newMountPath == null) {
11384                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11385                return false;
11386            }
11387            Log.i(TAG, "Succesfully renamed " + cid +
11388                    " to " + newCacheId +
11389                    " at new path: " + newMountPath);
11390            cid = newCacheId;
11391
11392            final File beforeCodeFile = new File(packagePath);
11393            setMountPath(newMountPath);
11394            final File afterCodeFile = new File(packagePath);
11395
11396            // Reflect the rename in scanned details
11397            pkg.codePath = afterCodeFile.getAbsolutePath();
11398            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11399                    pkg.baseCodePath);
11400            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11401                    pkg.splitCodePaths);
11402
11403            // Reflect the rename in app info
11404            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11405            pkg.applicationInfo.setCodePath(pkg.codePath);
11406            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11407            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11408            pkg.applicationInfo.setResourcePath(pkg.codePath);
11409            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11410            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11411
11412            return true;
11413        }
11414
11415        private void setMountPath(String mountPath) {
11416            final File mountFile = new File(mountPath);
11417
11418            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11419            if (monolithicFile.exists()) {
11420                packagePath = monolithicFile.getAbsolutePath();
11421                if (isFwdLocked()) {
11422                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11423                } else {
11424                    resourcePath = packagePath;
11425                }
11426            } else {
11427                packagePath = mountFile.getAbsolutePath();
11428                resourcePath = packagePath;
11429            }
11430        }
11431
11432        int doPostInstall(int status, int uid) {
11433            if (status != PackageManager.INSTALL_SUCCEEDED) {
11434                cleanUp();
11435            } else {
11436                final int groupOwner;
11437                final String protectedFile;
11438                if (isFwdLocked()) {
11439                    groupOwner = UserHandle.getSharedAppGid(uid);
11440                    protectedFile = RES_FILE_NAME;
11441                } else {
11442                    groupOwner = -1;
11443                    protectedFile = null;
11444                }
11445
11446                if (uid < Process.FIRST_APPLICATION_UID
11447                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11448                    Slog.e(TAG, "Failed to finalize " + cid);
11449                    PackageHelper.destroySdDir(cid);
11450                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11451                }
11452
11453                boolean mounted = PackageHelper.isContainerMounted(cid);
11454                if (!mounted) {
11455                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11456                }
11457            }
11458            return status;
11459        }
11460
11461        private void cleanUp() {
11462            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11463
11464            // Destroy secure container
11465            PackageHelper.destroySdDir(cid);
11466        }
11467
11468        private List<String> getAllCodePaths() {
11469            final File codeFile = new File(getCodePath());
11470            if (codeFile != null && codeFile.exists()) {
11471                try {
11472                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11473                    return pkg.getAllCodePaths();
11474                } catch (PackageParserException e) {
11475                    // Ignored; we tried our best
11476                }
11477            }
11478            return Collections.EMPTY_LIST;
11479        }
11480
11481        void cleanUpResourcesLI() {
11482            // Enumerate all code paths before deleting
11483            cleanUpResourcesLI(getAllCodePaths());
11484        }
11485
11486        private void cleanUpResourcesLI(List<String> allCodePaths) {
11487            cleanUp();
11488            removeDexFiles(allCodePaths, instructionSets);
11489        }
11490
11491        String getPackageName() {
11492            return getAsecPackageName(cid);
11493        }
11494
11495        boolean doPostDeleteLI(boolean delete) {
11496            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11497            final List<String> allCodePaths = getAllCodePaths();
11498            boolean mounted = PackageHelper.isContainerMounted(cid);
11499            if (mounted) {
11500                // Unmount first
11501                if (PackageHelper.unMountSdDir(cid)) {
11502                    mounted = false;
11503                }
11504            }
11505            if (!mounted && delete) {
11506                cleanUpResourcesLI(allCodePaths);
11507            }
11508            return !mounted;
11509        }
11510
11511        @Override
11512        int doPreCopy() {
11513            if (isFwdLocked()) {
11514                if (!PackageHelper.fixSdPermissions(cid,
11515                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11516                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11517                }
11518            }
11519
11520            return PackageManager.INSTALL_SUCCEEDED;
11521        }
11522
11523        @Override
11524        int doPostCopy(int uid) {
11525            if (isFwdLocked()) {
11526                if (uid < Process.FIRST_APPLICATION_UID
11527                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11528                                RES_FILE_NAME)) {
11529                    Slog.e(TAG, "Failed to finalize " + cid);
11530                    PackageHelper.destroySdDir(cid);
11531                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11532                }
11533            }
11534
11535            return PackageManager.INSTALL_SUCCEEDED;
11536        }
11537    }
11538
11539    /**
11540     * Logic to handle movement of existing installed applications.
11541     */
11542    class MoveInstallArgs extends InstallArgs {
11543        private File codeFile;
11544        private File resourceFile;
11545
11546        /** New install */
11547        MoveInstallArgs(InstallParams params) {
11548            super(params.origin, params.move, params.observer, params.installFlags,
11549                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11550                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11551                    params.grantedRuntimePermissions);
11552        }
11553
11554        int copyApk(IMediaContainerService imcs, boolean temp) {
11555            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11556                    + move.fromUuid + " to " + move.toUuid);
11557            synchronized (mInstaller) {
11558                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11559                        move.dataAppName, move.appId, move.seinfo) != 0) {
11560                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11561                }
11562            }
11563
11564            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11565            resourceFile = codeFile;
11566            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11567
11568            return PackageManager.INSTALL_SUCCEEDED;
11569        }
11570
11571        int doPreInstall(int status) {
11572            if (status != PackageManager.INSTALL_SUCCEEDED) {
11573                cleanUp(move.toUuid);
11574            }
11575            return status;
11576        }
11577
11578        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11579            if (status != PackageManager.INSTALL_SUCCEEDED) {
11580                cleanUp(move.toUuid);
11581                return false;
11582            }
11583
11584            // Reflect the move in app info
11585            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11586            pkg.applicationInfo.setCodePath(pkg.codePath);
11587            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11588            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11589            pkg.applicationInfo.setResourcePath(pkg.codePath);
11590            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11591            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11592
11593            return true;
11594        }
11595
11596        int doPostInstall(int status, int uid) {
11597            if (status == PackageManager.INSTALL_SUCCEEDED) {
11598                cleanUp(move.fromUuid);
11599            } else {
11600                cleanUp(move.toUuid);
11601            }
11602            return status;
11603        }
11604
11605        @Override
11606        String getCodePath() {
11607            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11608        }
11609
11610        @Override
11611        String getResourcePath() {
11612            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11613        }
11614
11615        private boolean cleanUp(String volumeUuid) {
11616            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11617                    move.dataAppName);
11618            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11619            synchronized (mInstallLock) {
11620                // Clean up both app data and code
11621                removeDataDirsLI(volumeUuid, move.packageName);
11622                if (codeFile.isDirectory()) {
11623                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11624                } else {
11625                    codeFile.delete();
11626                }
11627            }
11628            return true;
11629        }
11630
11631        void cleanUpResourcesLI() {
11632            throw new UnsupportedOperationException();
11633        }
11634
11635        boolean doPostDeleteLI(boolean delete) {
11636            throw new UnsupportedOperationException();
11637        }
11638    }
11639
11640    static String getAsecPackageName(String packageCid) {
11641        int idx = packageCid.lastIndexOf("-");
11642        if (idx == -1) {
11643            return packageCid;
11644        }
11645        return packageCid.substring(0, idx);
11646    }
11647
11648    // Utility method used to create code paths based on package name and available index.
11649    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11650        String idxStr = "";
11651        int idx = 1;
11652        // Fall back to default value of idx=1 if prefix is not
11653        // part of oldCodePath
11654        if (oldCodePath != null) {
11655            String subStr = oldCodePath;
11656            // Drop the suffix right away
11657            if (suffix != null && subStr.endsWith(suffix)) {
11658                subStr = subStr.substring(0, subStr.length() - suffix.length());
11659            }
11660            // If oldCodePath already contains prefix find out the
11661            // ending index to either increment or decrement.
11662            int sidx = subStr.lastIndexOf(prefix);
11663            if (sidx != -1) {
11664                subStr = subStr.substring(sidx + prefix.length());
11665                if (subStr != null) {
11666                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11667                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11668                    }
11669                    try {
11670                        idx = Integer.parseInt(subStr);
11671                        if (idx <= 1) {
11672                            idx++;
11673                        } else {
11674                            idx--;
11675                        }
11676                    } catch(NumberFormatException e) {
11677                    }
11678                }
11679            }
11680        }
11681        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11682        return prefix + idxStr;
11683    }
11684
11685    private File getNextCodePath(File targetDir, String packageName) {
11686        int suffix = 1;
11687        File result;
11688        do {
11689            result = new File(targetDir, packageName + "-" + suffix);
11690            suffix++;
11691        } while (result.exists());
11692        return result;
11693    }
11694
11695    // Utility method that returns the relative package path with respect
11696    // to the installation directory. Like say for /data/data/com.test-1.apk
11697    // string com.test-1 is returned.
11698    static String deriveCodePathName(String codePath) {
11699        if (codePath == null) {
11700            return null;
11701        }
11702        final File codeFile = new File(codePath);
11703        final String name = codeFile.getName();
11704        if (codeFile.isDirectory()) {
11705            return name;
11706        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11707            final int lastDot = name.lastIndexOf('.');
11708            return name.substring(0, lastDot);
11709        } else {
11710            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11711            return null;
11712        }
11713    }
11714
11715    class PackageInstalledInfo {
11716        String name;
11717        int uid;
11718        // The set of users that originally had this package installed.
11719        int[] origUsers;
11720        // The set of users that now have this package installed.
11721        int[] newUsers;
11722        PackageParser.Package pkg;
11723        int returnCode;
11724        String returnMsg;
11725        PackageRemovedInfo removedInfo;
11726
11727        public void setError(int code, String msg) {
11728            returnCode = code;
11729            returnMsg = msg;
11730            Slog.w(TAG, msg);
11731        }
11732
11733        public void setError(String msg, PackageParserException e) {
11734            returnCode = e.error;
11735            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11736            Slog.w(TAG, msg, e);
11737        }
11738
11739        public void setError(String msg, PackageManagerException e) {
11740            returnCode = e.error;
11741            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11742            Slog.w(TAG, msg, e);
11743        }
11744
11745        // In some error cases we want to convey more info back to the observer
11746        String origPackage;
11747        String origPermission;
11748    }
11749
11750    /*
11751     * Install a non-existing package.
11752     */
11753    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11754            UserHandle user, String installerPackageName, String volumeUuid,
11755            PackageInstalledInfo res) {
11756        // Remember this for later, in case we need to rollback this install
11757        String pkgName = pkg.packageName;
11758
11759        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11760        final boolean dataDirExists = Environment
11761                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11762        synchronized(mPackages) {
11763            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11764                // A package with the same name is already installed, though
11765                // it has been renamed to an older name.  The package we
11766                // are trying to install should be installed as an update to
11767                // the existing one, but that has not been requested, so bail.
11768                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11769                        + " without first uninstalling package running as "
11770                        + mSettings.mRenamedPackages.get(pkgName));
11771                return;
11772            }
11773            if (mPackages.containsKey(pkgName)) {
11774                // Don't allow installation over an existing package with the same name.
11775                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11776                        + " without first uninstalling.");
11777                return;
11778            }
11779        }
11780
11781        try {
11782            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11783                    System.currentTimeMillis(), user);
11784
11785            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11786            // delete the partially installed application. the data directory will have to be
11787            // restored if it was already existing
11788            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11789                // remove package from internal structures.  Note that we want deletePackageX to
11790                // delete the package data and cache directories that it created in
11791                // scanPackageLocked, unless those directories existed before we even tried to
11792                // install.
11793                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11794                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11795                                res.removedInfo, true);
11796            }
11797
11798        } catch (PackageManagerException e) {
11799            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11800        }
11801    }
11802
11803    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11804        // Can't rotate keys during boot or if sharedUser.
11805        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11806                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11807            return false;
11808        }
11809        // app is using upgradeKeySets; make sure all are valid
11810        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11811        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11812        for (int i = 0; i < upgradeKeySets.length; i++) {
11813            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11814                Slog.wtf(TAG, "Package "
11815                         + (oldPs.name != null ? oldPs.name : "<null>")
11816                         + " contains upgrade-key-set reference to unknown key-set: "
11817                         + upgradeKeySets[i]
11818                         + " reverting to signatures check.");
11819                return false;
11820            }
11821        }
11822        return true;
11823    }
11824
11825    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11826        // Upgrade keysets are being used.  Determine if new package has a superset of the
11827        // required keys.
11828        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11829        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11830        for (int i = 0; i < upgradeKeySets.length; i++) {
11831            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11832            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11833                return true;
11834            }
11835        }
11836        return false;
11837    }
11838
11839    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11840            UserHandle user, String installerPackageName, String volumeUuid,
11841            PackageInstalledInfo res) {
11842        final PackageParser.Package oldPackage;
11843        final String pkgName = pkg.packageName;
11844        final int[] allUsers;
11845        final boolean[] perUserInstalled;
11846
11847        // First find the old package info and check signatures
11848        synchronized(mPackages) {
11849            oldPackage = mPackages.get(pkgName);
11850            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11851            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11852            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11853                if(!checkUpgradeKeySetLP(ps, pkg)) {
11854                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11855                            "New package not signed by keys specified by upgrade-keysets: "
11856                            + pkgName);
11857                    return;
11858                }
11859            } else {
11860                // default to original signature matching
11861                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11862                    != PackageManager.SIGNATURE_MATCH) {
11863                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11864                            "New package has a different signature: " + pkgName);
11865                    return;
11866                }
11867            }
11868
11869            // In case of rollback, remember per-user/profile install state
11870            allUsers = sUserManager.getUserIds();
11871            perUserInstalled = new boolean[allUsers.length];
11872            for (int i = 0; i < allUsers.length; i++) {
11873                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11874            }
11875        }
11876
11877        boolean sysPkg = (isSystemApp(oldPackage));
11878        if (sysPkg) {
11879            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11880                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11881        } else {
11882            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11883                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11884        }
11885    }
11886
11887    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11888            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11889            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11890            String volumeUuid, PackageInstalledInfo res) {
11891        String pkgName = deletedPackage.packageName;
11892        boolean deletedPkg = true;
11893        boolean updatedSettings = false;
11894
11895        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11896                + deletedPackage);
11897        long origUpdateTime;
11898        if (pkg.mExtras != null) {
11899            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11900        } else {
11901            origUpdateTime = 0;
11902        }
11903
11904        // First delete the existing package while retaining the data directory
11905        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11906                res.removedInfo, true)) {
11907            // If the existing package wasn't successfully deleted
11908            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11909            deletedPkg = false;
11910        } else {
11911            // Successfully deleted the old package; proceed with replace.
11912
11913            // If deleted package lived in a container, give users a chance to
11914            // relinquish resources before killing.
11915            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11916                if (DEBUG_INSTALL) {
11917                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11918                }
11919                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11920                final ArrayList<String> pkgList = new ArrayList<String>(1);
11921                pkgList.add(deletedPackage.applicationInfo.packageName);
11922                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11923            }
11924
11925            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11926            try {
11927                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11928                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11929                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11930                        perUserInstalled, res, user);
11931                updatedSettings = true;
11932            } catch (PackageManagerException e) {
11933                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11934            }
11935        }
11936
11937        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11938            // remove package from internal structures.  Note that we want deletePackageX to
11939            // delete the package data and cache directories that it created in
11940            // scanPackageLocked, unless those directories existed before we even tried to
11941            // install.
11942            if(updatedSettings) {
11943                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11944                deletePackageLI(
11945                        pkgName, null, true, allUsers, perUserInstalled,
11946                        PackageManager.DELETE_KEEP_DATA,
11947                                res.removedInfo, true);
11948            }
11949            // Since we failed to install the new package we need to restore the old
11950            // package that we deleted.
11951            if (deletedPkg) {
11952                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11953                File restoreFile = new File(deletedPackage.codePath);
11954                // Parse old package
11955                boolean oldExternal = isExternal(deletedPackage);
11956                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11957                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11958                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11959                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11960                try {
11961                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11962                } catch (PackageManagerException e) {
11963                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11964                            + e.getMessage());
11965                    return;
11966                }
11967                // Restore of old package succeeded. Update permissions.
11968                // writer
11969                synchronized (mPackages) {
11970                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11971                            UPDATE_PERMISSIONS_ALL);
11972                    // can downgrade to reader
11973                    mSettings.writeLPr();
11974                }
11975                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11976            }
11977        }
11978    }
11979
11980    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11981            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11982            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11983            String volumeUuid, PackageInstalledInfo res) {
11984        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11985                + ", old=" + deletedPackage);
11986        boolean disabledSystem = false;
11987        boolean updatedSettings = false;
11988        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11989        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11990                != 0) {
11991            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11992        }
11993        String packageName = deletedPackage.packageName;
11994        if (packageName == null) {
11995            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11996                    "Attempt to delete null packageName.");
11997            return;
11998        }
11999        PackageParser.Package oldPkg;
12000        PackageSetting oldPkgSetting;
12001        // reader
12002        synchronized (mPackages) {
12003            oldPkg = mPackages.get(packageName);
12004            oldPkgSetting = mSettings.mPackages.get(packageName);
12005            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12006                    (oldPkgSetting == null)) {
12007                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12008                        "Couldn't find package:" + packageName + " information");
12009                return;
12010            }
12011        }
12012
12013        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12014
12015        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12016        res.removedInfo.removedPackage = packageName;
12017        // Remove existing system package
12018        removePackageLI(oldPkgSetting, true);
12019        // writer
12020        synchronized (mPackages) {
12021            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12022            if (!disabledSystem && deletedPackage != null) {
12023                // We didn't need to disable the .apk as a current system package,
12024                // which means we are replacing another update that is already
12025                // installed.  We need to make sure to delete the older one's .apk.
12026                res.removedInfo.args = createInstallArgsForExisting(0,
12027                        deletedPackage.applicationInfo.getCodePath(),
12028                        deletedPackage.applicationInfo.getResourcePath(),
12029                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12030            } else {
12031                res.removedInfo.args = null;
12032            }
12033        }
12034
12035        // Successfully disabled the old package. Now proceed with re-installation
12036        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12037
12038        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12039        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12040
12041        PackageParser.Package newPackage = null;
12042        try {
12043            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12044            if (newPackage.mExtras != null) {
12045                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12046                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12047                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12048
12049                // is the update attempting to change shared user? that isn't going to work...
12050                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12051                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12052                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12053                            + " to " + newPkgSetting.sharedUser);
12054                    updatedSettings = true;
12055                }
12056            }
12057
12058            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12059                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12060                        perUserInstalled, res, user);
12061                updatedSettings = true;
12062            }
12063
12064        } catch (PackageManagerException e) {
12065            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12066        }
12067
12068        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12069            // Re installation failed. Restore old information
12070            // Remove new pkg information
12071            if (newPackage != null) {
12072                removeInstalledPackageLI(newPackage, true);
12073            }
12074            // Add back the old system package
12075            try {
12076                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12077            } catch (PackageManagerException e) {
12078                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12079            }
12080            // Restore the old system information in Settings
12081            synchronized (mPackages) {
12082                if (disabledSystem) {
12083                    mSettings.enableSystemPackageLPw(packageName);
12084                }
12085                if (updatedSettings) {
12086                    mSettings.setInstallerPackageName(packageName,
12087                            oldPkgSetting.installerPackageName);
12088                }
12089                mSettings.writeLPr();
12090            }
12091        }
12092    }
12093
12094    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12095            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12096            UserHandle user) {
12097        String pkgName = newPackage.packageName;
12098        synchronized (mPackages) {
12099            //write settings. the installStatus will be incomplete at this stage.
12100            //note that the new package setting would have already been
12101            //added to mPackages. It hasn't been persisted yet.
12102            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12103            mSettings.writeLPr();
12104        }
12105
12106        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12107
12108        synchronized (mPackages) {
12109            updatePermissionsLPw(newPackage.packageName, newPackage,
12110                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12111                            ? UPDATE_PERMISSIONS_ALL : 0));
12112            // For system-bundled packages, we assume that installing an upgraded version
12113            // of the package implies that the user actually wants to run that new code,
12114            // so we enable the package.
12115            PackageSetting ps = mSettings.mPackages.get(pkgName);
12116            if (ps != null) {
12117                if (isSystemApp(newPackage)) {
12118                    // NB: implicit assumption that system package upgrades apply to all users
12119                    if (DEBUG_INSTALL) {
12120                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12121                    }
12122                    if (res.origUsers != null) {
12123                        for (int userHandle : res.origUsers) {
12124                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12125                                    userHandle, installerPackageName);
12126                        }
12127                    }
12128                    // Also convey the prior install/uninstall state
12129                    if (allUsers != null && perUserInstalled != null) {
12130                        for (int i = 0; i < allUsers.length; i++) {
12131                            if (DEBUG_INSTALL) {
12132                                Slog.d(TAG, "    user " + allUsers[i]
12133                                        + " => " + perUserInstalled[i]);
12134                            }
12135                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12136                        }
12137                        // these install state changes will be persisted in the
12138                        // upcoming call to mSettings.writeLPr().
12139                    }
12140                }
12141                // It's implied that when a user requests installation, they want the app to be
12142                // installed and enabled.
12143                int userId = user.getIdentifier();
12144                if (userId != UserHandle.USER_ALL) {
12145                    ps.setInstalled(true, userId);
12146                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12147                }
12148            }
12149            res.name = pkgName;
12150            res.uid = newPackage.applicationInfo.uid;
12151            res.pkg = newPackage;
12152            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12153            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12154            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12155            //to update install status
12156            mSettings.writeLPr();
12157        }
12158    }
12159
12160    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12161        final int installFlags = args.installFlags;
12162        final String installerPackageName = args.installerPackageName;
12163        final String volumeUuid = args.volumeUuid;
12164        final File tmpPackageFile = new File(args.getCodePath());
12165        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12166        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12167                || (args.volumeUuid != null));
12168        boolean replace = false;
12169        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12170        if (args.move != null) {
12171            // moving a complete application; perfom an initial scan on the new install location
12172            scanFlags |= SCAN_INITIAL;
12173        }
12174        // Result object to be returned
12175        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12176
12177        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12178        // Retrieve PackageSettings and parse package
12179        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12180                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12181                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12182        PackageParser pp = new PackageParser();
12183        pp.setSeparateProcesses(mSeparateProcesses);
12184        pp.setDisplayMetrics(mMetrics);
12185
12186        final PackageParser.Package pkg;
12187        try {
12188            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12189        } catch (PackageParserException e) {
12190            res.setError("Failed parse during installPackageLI", e);
12191            return;
12192        }
12193
12194        // Mark that we have an install time CPU ABI override.
12195        pkg.cpuAbiOverride = args.abiOverride;
12196
12197        String pkgName = res.name = pkg.packageName;
12198        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12199            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12200                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12201                return;
12202            }
12203        }
12204
12205        try {
12206            pp.collectCertificates(pkg, parseFlags);
12207            pp.collectManifestDigest(pkg);
12208        } catch (PackageParserException e) {
12209            res.setError("Failed collect during installPackageLI", e);
12210            return;
12211        }
12212
12213        /* If the installer passed in a manifest digest, compare it now. */
12214        if (args.manifestDigest != null) {
12215            if (DEBUG_INSTALL) {
12216                final String parsedManifest = pkg.manifestDigest == null ? "null"
12217                        : pkg.manifestDigest.toString();
12218                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12219                        + parsedManifest);
12220            }
12221
12222            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12223                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12224                return;
12225            }
12226        } else if (DEBUG_INSTALL) {
12227            final String parsedManifest = pkg.manifestDigest == null
12228                    ? "null" : pkg.manifestDigest.toString();
12229            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12230        }
12231
12232        // Get rid of all references to package scan path via parser.
12233        pp = null;
12234        String oldCodePath = null;
12235        boolean systemApp = false;
12236        synchronized (mPackages) {
12237            // Check if installing already existing package
12238            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12239                String oldName = mSettings.mRenamedPackages.get(pkgName);
12240                if (pkg.mOriginalPackages != null
12241                        && pkg.mOriginalPackages.contains(oldName)
12242                        && mPackages.containsKey(oldName)) {
12243                    // This package is derived from an original package,
12244                    // and this device has been updating from that original
12245                    // name.  We must continue using the original name, so
12246                    // rename the new package here.
12247                    pkg.setPackageName(oldName);
12248                    pkgName = pkg.packageName;
12249                    replace = true;
12250                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12251                            + oldName + " pkgName=" + pkgName);
12252                } else if (mPackages.containsKey(pkgName)) {
12253                    // This package, under its official name, already exists
12254                    // on the device; we should replace it.
12255                    replace = true;
12256                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12257                }
12258
12259                // Prevent apps opting out from runtime permissions
12260                if (replace) {
12261                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12262                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12263                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12264                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12265                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12266                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12267                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12268                                        + " doesn't support runtime permissions but the old"
12269                                        + " target SDK " + oldTargetSdk + " does.");
12270                        return;
12271                    }
12272                }
12273            }
12274
12275            PackageSetting ps = mSettings.mPackages.get(pkgName);
12276            if (ps != null) {
12277                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12278
12279                // Quick sanity check that we're signed correctly if updating;
12280                // we'll check this again later when scanning, but we want to
12281                // bail early here before tripping over redefined permissions.
12282                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12283                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12284                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12285                                + pkg.packageName + " upgrade keys do not match the "
12286                                + "previously installed version");
12287                        return;
12288                    }
12289                } else {
12290                    try {
12291                        verifySignaturesLP(ps, pkg);
12292                    } catch (PackageManagerException e) {
12293                        res.setError(e.error, e.getMessage());
12294                        return;
12295                    }
12296                }
12297
12298                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12299                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12300                    systemApp = (ps.pkg.applicationInfo.flags &
12301                            ApplicationInfo.FLAG_SYSTEM) != 0;
12302                }
12303                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12304            }
12305
12306            // Check whether the newly-scanned package wants to define an already-defined perm
12307            int N = pkg.permissions.size();
12308            for (int i = N-1; i >= 0; i--) {
12309                PackageParser.Permission perm = pkg.permissions.get(i);
12310                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12311                if (bp != null) {
12312                    // If the defining package is signed with our cert, it's okay.  This
12313                    // also includes the "updating the same package" case, of course.
12314                    // "updating same package" could also involve key-rotation.
12315                    final boolean sigsOk;
12316                    if (bp.sourcePackage.equals(pkg.packageName)
12317                            && (bp.packageSetting instanceof PackageSetting)
12318                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12319                                    scanFlags))) {
12320                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12321                    } else {
12322                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12323                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12324                    }
12325                    if (!sigsOk) {
12326                        // If the owning package is the system itself, we log but allow
12327                        // install to proceed; we fail the install on all other permission
12328                        // redefinitions.
12329                        if (!bp.sourcePackage.equals("android")) {
12330                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12331                                    + pkg.packageName + " attempting to redeclare permission "
12332                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12333                            res.origPermission = perm.info.name;
12334                            res.origPackage = bp.sourcePackage;
12335                            return;
12336                        } else {
12337                            Slog.w(TAG, "Package " + pkg.packageName
12338                                    + " attempting to redeclare system permission "
12339                                    + perm.info.name + "; ignoring new declaration");
12340                            pkg.permissions.remove(i);
12341                        }
12342                    }
12343                }
12344            }
12345
12346        }
12347
12348        if (systemApp && onExternal) {
12349            // Disable updates to system apps on sdcard
12350            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12351                    "Cannot install updates to system apps on sdcard");
12352            return;
12353        }
12354
12355        if (args.move != null) {
12356            // We did an in-place move, so dex is ready to roll
12357            scanFlags |= SCAN_NO_DEX;
12358            scanFlags |= SCAN_MOVE;
12359
12360            synchronized (mPackages) {
12361                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12362                if (ps == null) {
12363                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12364                            "Missing settings for moved package " + pkgName);
12365                }
12366
12367                // We moved the entire application as-is, so bring over the
12368                // previously derived ABI information.
12369                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12370                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12371            }
12372
12373        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12374            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12375            scanFlags |= SCAN_NO_DEX;
12376
12377            try {
12378                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12379                        true /* extract libs */);
12380            } catch (PackageManagerException pme) {
12381                Slog.e(TAG, "Error deriving application ABI", pme);
12382                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12383                return;
12384            }
12385
12386            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12387            int result = mPackageDexOptimizer
12388                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12389                            false /* defer */, false /* inclDependencies */,
12390                            true /* boot complete */);
12391            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12392                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12393                return;
12394            }
12395        }
12396
12397        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12398            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12399            return;
12400        }
12401
12402        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12403
12404        if (replace) {
12405            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12406                    installerPackageName, volumeUuid, res);
12407        } else {
12408            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12409                    args.user, installerPackageName, volumeUuid, res);
12410        }
12411        synchronized (mPackages) {
12412            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12413            if (ps != null) {
12414                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12415            }
12416        }
12417    }
12418
12419    private void startIntentFilterVerifications(int userId, boolean replacing,
12420            PackageParser.Package pkg) {
12421        if (mIntentFilterVerifierComponent == null) {
12422            Slog.w(TAG, "No IntentFilter verification will not be done as "
12423                    + "there is no IntentFilterVerifier available!");
12424            return;
12425        }
12426
12427        final int verifierUid = getPackageUid(
12428                mIntentFilterVerifierComponent.getPackageName(),
12429                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12430
12431        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12432        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12433        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12434        mHandler.sendMessage(msg);
12435    }
12436
12437    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12438            PackageParser.Package pkg) {
12439        int size = pkg.activities.size();
12440        if (size == 0) {
12441            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12442                    "No activity, so no need to verify any IntentFilter!");
12443            return;
12444        }
12445
12446        final boolean hasDomainURLs = hasDomainURLs(pkg);
12447        if (!hasDomainURLs) {
12448            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12449                    "No domain URLs, so no need to verify any IntentFilter!");
12450            return;
12451        }
12452
12453        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12454                + " if any IntentFilter from the " + size
12455                + " Activities needs verification ...");
12456
12457        int count = 0;
12458        final String packageName = pkg.packageName;
12459
12460        synchronized (mPackages) {
12461            // If this is a new install and we see that we've already run verification for this
12462            // package, we have nothing to do: it means the state was restored from backup.
12463            if (!replacing) {
12464                IntentFilterVerificationInfo ivi =
12465                        mSettings.getIntentFilterVerificationLPr(packageName);
12466                if (ivi != null) {
12467                    if (DEBUG_DOMAIN_VERIFICATION) {
12468                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12469                                + ivi.getStatusString());
12470                    }
12471                    return;
12472                }
12473            }
12474
12475            // If any filters need to be verified, then all need to be.
12476            boolean needToVerify = false;
12477            for (PackageParser.Activity a : pkg.activities) {
12478                for (ActivityIntentInfo filter : a.intents) {
12479                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12480                        if (DEBUG_DOMAIN_VERIFICATION) {
12481                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12482                        }
12483                        needToVerify = true;
12484                        break;
12485                    }
12486                }
12487            }
12488
12489            if (needToVerify) {
12490                final int verificationId = mIntentFilterVerificationToken++;
12491                for (PackageParser.Activity a : pkg.activities) {
12492                    for (ActivityIntentInfo filter : a.intents) {
12493                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12494                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12495                                    "Verification needed for IntentFilter:" + filter.toString());
12496                            mIntentFilterVerifier.addOneIntentFilterVerification(
12497                                    verifierUid, userId, verificationId, filter, packageName);
12498                            count++;
12499                        }
12500                    }
12501                }
12502            }
12503        }
12504
12505        if (count > 0) {
12506            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12507                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12508                    +  " for userId:" + userId);
12509            mIntentFilterVerifier.startVerifications(userId);
12510        } else {
12511            if (DEBUG_DOMAIN_VERIFICATION) {
12512                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12513            }
12514        }
12515    }
12516
12517    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12518        final ComponentName cn  = filter.activity.getComponentName();
12519        final String packageName = cn.getPackageName();
12520
12521        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12522                packageName);
12523        if (ivi == null) {
12524            return true;
12525        }
12526        int status = ivi.getStatus();
12527        switch (status) {
12528            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12529            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12530                return true;
12531
12532            default:
12533                // Nothing to do
12534                return false;
12535        }
12536    }
12537
12538    private static boolean isMultiArch(PackageSetting ps) {
12539        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12540    }
12541
12542    private static boolean isMultiArch(ApplicationInfo info) {
12543        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12544    }
12545
12546    private static boolean isExternal(PackageParser.Package pkg) {
12547        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12548    }
12549
12550    private static boolean isExternal(PackageSetting ps) {
12551        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12552    }
12553
12554    private static boolean isExternal(ApplicationInfo info) {
12555        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12556    }
12557
12558    private static boolean isSystemApp(PackageParser.Package pkg) {
12559        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12560    }
12561
12562    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12563        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12564    }
12565
12566    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12567        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12568    }
12569
12570    private static boolean isSystemApp(PackageSetting ps) {
12571        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12572    }
12573
12574    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12575        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12576    }
12577
12578    private int packageFlagsToInstallFlags(PackageSetting ps) {
12579        int installFlags = 0;
12580        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12581            // This existing package was an external ASEC install when we have
12582            // the external flag without a UUID
12583            installFlags |= PackageManager.INSTALL_EXTERNAL;
12584        }
12585        if (ps.isForwardLocked()) {
12586            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12587        }
12588        return installFlags;
12589    }
12590
12591    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12592        if (isExternal(pkg)) {
12593            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12594                return mSettings.getExternalVersion();
12595            } else {
12596                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12597            }
12598        } else {
12599            return mSettings.getInternalVersion();
12600        }
12601    }
12602
12603    private void deleteTempPackageFiles() {
12604        final FilenameFilter filter = new FilenameFilter() {
12605            public boolean accept(File dir, String name) {
12606                return name.startsWith("vmdl") && name.endsWith(".tmp");
12607            }
12608        };
12609        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12610            file.delete();
12611        }
12612    }
12613
12614    @Override
12615    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12616            int flags) {
12617        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12618                flags);
12619    }
12620
12621    @Override
12622    public void deletePackage(final String packageName,
12623            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12624        mContext.enforceCallingOrSelfPermission(
12625                android.Manifest.permission.DELETE_PACKAGES, null);
12626        Preconditions.checkNotNull(packageName);
12627        Preconditions.checkNotNull(observer);
12628        final int uid = Binder.getCallingUid();
12629        if (UserHandle.getUserId(uid) != userId) {
12630            mContext.enforceCallingPermission(
12631                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12632                    "deletePackage for user " + userId);
12633        }
12634        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12635            try {
12636                observer.onPackageDeleted(packageName,
12637                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12638            } catch (RemoteException re) {
12639            }
12640            return;
12641        }
12642
12643        boolean uninstallBlocked = false;
12644        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12645            int[] users = sUserManager.getUserIds();
12646            for (int i = 0; i < users.length; ++i) {
12647                if (getBlockUninstallForUser(packageName, users[i])) {
12648                    uninstallBlocked = true;
12649                    break;
12650                }
12651            }
12652        } else {
12653            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12654        }
12655        if (uninstallBlocked) {
12656            try {
12657                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12658                        null);
12659            } catch (RemoteException re) {
12660            }
12661            return;
12662        }
12663
12664        if (DEBUG_REMOVE) {
12665            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12666        }
12667        // Queue up an async operation since the package deletion may take a little while.
12668        mHandler.post(new Runnable() {
12669            public void run() {
12670                mHandler.removeCallbacks(this);
12671                final int returnCode = deletePackageX(packageName, userId, flags);
12672                if (observer != null) {
12673                    try {
12674                        observer.onPackageDeleted(packageName, returnCode, null);
12675                    } catch (RemoteException e) {
12676                        Log.i(TAG, "Observer no longer exists.");
12677                    } //end catch
12678                } //end if
12679            } //end run
12680        });
12681    }
12682
12683    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12684        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12685                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12686        try {
12687            if (dpm != null) {
12688                if (dpm.isDeviceOwner(packageName)) {
12689                    return true;
12690                }
12691                int[] users;
12692                if (userId == UserHandle.USER_ALL) {
12693                    users = sUserManager.getUserIds();
12694                } else {
12695                    users = new int[]{userId};
12696                }
12697                for (int i = 0; i < users.length; ++i) {
12698                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12699                        return true;
12700                    }
12701                }
12702            }
12703        } catch (RemoteException e) {
12704        }
12705        return false;
12706    }
12707
12708    /**
12709     *  This method is an internal method that could be get invoked either
12710     *  to delete an installed package or to clean up a failed installation.
12711     *  After deleting an installed package, a broadcast is sent to notify any
12712     *  listeners that the package has been installed. For cleaning up a failed
12713     *  installation, the broadcast is not necessary since the package's
12714     *  installation wouldn't have sent the initial broadcast either
12715     *  The key steps in deleting a package are
12716     *  deleting the package information in internal structures like mPackages,
12717     *  deleting the packages base directories through installd
12718     *  updating mSettings to reflect current status
12719     *  persisting settings for later use
12720     *  sending a broadcast if necessary
12721     */
12722    private int deletePackageX(String packageName, int userId, int flags) {
12723        final PackageRemovedInfo info = new PackageRemovedInfo();
12724        final boolean res;
12725
12726        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12727                ? UserHandle.ALL : new UserHandle(userId);
12728
12729        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12730            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12731            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12732        }
12733
12734        boolean removedForAllUsers = false;
12735        boolean systemUpdate = false;
12736
12737        // for the uninstall-updates case and restricted profiles, remember the per-
12738        // userhandle installed state
12739        int[] allUsers;
12740        boolean[] perUserInstalled;
12741        synchronized (mPackages) {
12742            PackageSetting ps = mSettings.mPackages.get(packageName);
12743            allUsers = sUserManager.getUserIds();
12744            perUserInstalled = new boolean[allUsers.length];
12745            for (int i = 0; i < allUsers.length; i++) {
12746                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12747            }
12748        }
12749
12750        synchronized (mInstallLock) {
12751            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12752            res = deletePackageLI(packageName, removeForUser,
12753                    true, allUsers, perUserInstalled,
12754                    flags | REMOVE_CHATTY, info, true);
12755            systemUpdate = info.isRemovedPackageSystemUpdate;
12756            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12757                removedForAllUsers = true;
12758            }
12759            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12760                    + " removedForAllUsers=" + removedForAllUsers);
12761        }
12762
12763        if (res) {
12764            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12765
12766            // If the removed package was a system update, the old system package
12767            // was re-enabled; we need to broadcast this information
12768            if (systemUpdate) {
12769                Bundle extras = new Bundle(1);
12770                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12771                        ? info.removedAppId : info.uid);
12772                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12773
12774                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12775                        extras, null, null, null);
12776                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12777                        extras, null, null, null);
12778                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12779                        null, packageName, null, null);
12780            }
12781        }
12782        // Force a gc here.
12783        Runtime.getRuntime().gc();
12784        // Delete the resources here after sending the broadcast to let
12785        // other processes clean up before deleting resources.
12786        if (info.args != null) {
12787            synchronized (mInstallLock) {
12788                info.args.doPostDeleteLI(true);
12789            }
12790        }
12791
12792        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12793    }
12794
12795    class PackageRemovedInfo {
12796        String removedPackage;
12797        int uid = -1;
12798        int removedAppId = -1;
12799        int[] removedUsers = null;
12800        boolean isRemovedPackageSystemUpdate = false;
12801        // Clean up resources deleted packages.
12802        InstallArgs args = null;
12803
12804        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12805            Bundle extras = new Bundle(1);
12806            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12807            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12808            if (replacing) {
12809                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12810            }
12811            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12812            if (removedPackage != null) {
12813                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12814                        extras, null, null, removedUsers);
12815                if (fullRemove && !replacing) {
12816                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12817                            extras, null, null, removedUsers);
12818                }
12819            }
12820            if (removedAppId >= 0) {
12821                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12822                        removedUsers);
12823            }
12824        }
12825    }
12826
12827    /*
12828     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12829     * flag is not set, the data directory is removed as well.
12830     * make sure this flag is set for partially installed apps. If not its meaningless to
12831     * delete a partially installed application.
12832     */
12833    private void removePackageDataLI(PackageSetting ps,
12834            int[] allUserHandles, boolean[] perUserInstalled,
12835            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12836        String packageName = ps.name;
12837        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12838        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12839        // Retrieve object to delete permissions for shared user later on
12840        final PackageSetting deletedPs;
12841        // reader
12842        synchronized (mPackages) {
12843            deletedPs = mSettings.mPackages.get(packageName);
12844            if (outInfo != null) {
12845                outInfo.removedPackage = packageName;
12846                outInfo.removedUsers = deletedPs != null
12847                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12848                        : null;
12849            }
12850        }
12851        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12852            removeDataDirsLI(ps.volumeUuid, packageName);
12853            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12854        }
12855        // writer
12856        synchronized (mPackages) {
12857            if (deletedPs != null) {
12858                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12859                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12860                    clearDefaultBrowserIfNeeded(packageName);
12861                    if (outInfo != null) {
12862                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12863                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12864                    }
12865                    updatePermissionsLPw(deletedPs.name, null, 0);
12866                    if (deletedPs.sharedUser != null) {
12867                        // Remove permissions associated with package. Since runtime
12868                        // permissions are per user we have to kill the removed package
12869                        // or packages running under the shared user of the removed
12870                        // package if revoking the permissions requested only by the removed
12871                        // package is successful and this causes a change in gids.
12872                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12873                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12874                                    userId);
12875                            if (userIdToKill == UserHandle.USER_ALL
12876                                    || userIdToKill >= UserHandle.USER_OWNER) {
12877                                // If gids changed for this user, kill all affected packages.
12878                                mHandler.post(new Runnable() {
12879                                    @Override
12880                                    public void run() {
12881                                        // This has to happen with no lock held.
12882                                        killApplication(deletedPs.name, deletedPs.appId,
12883                                                KILL_APP_REASON_GIDS_CHANGED);
12884                                    }
12885                                });
12886                                break;
12887                            }
12888                        }
12889                    }
12890                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12891                }
12892                // make sure to preserve per-user disabled state if this removal was just
12893                // a downgrade of a system app to the factory package
12894                if (allUserHandles != null && perUserInstalled != null) {
12895                    if (DEBUG_REMOVE) {
12896                        Slog.d(TAG, "Propagating install state across downgrade");
12897                    }
12898                    for (int i = 0; i < allUserHandles.length; i++) {
12899                        if (DEBUG_REMOVE) {
12900                            Slog.d(TAG, "    user " + allUserHandles[i]
12901                                    + " => " + perUserInstalled[i]);
12902                        }
12903                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12904                    }
12905                }
12906            }
12907            // can downgrade to reader
12908            if (writeSettings) {
12909                // Save settings now
12910                mSettings.writeLPr();
12911            }
12912        }
12913        if (outInfo != null) {
12914            // A user ID was deleted here. Go through all users and remove it
12915            // from KeyStore.
12916            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12917        }
12918    }
12919
12920    static boolean locationIsPrivileged(File path) {
12921        try {
12922            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12923                    .getCanonicalPath();
12924            return path.getCanonicalPath().startsWith(privilegedAppDir);
12925        } catch (IOException e) {
12926            Slog.e(TAG, "Unable to access code path " + path);
12927        }
12928        return false;
12929    }
12930
12931    /*
12932     * Tries to delete system package.
12933     */
12934    private boolean deleteSystemPackageLI(PackageSetting newPs,
12935            int[] allUserHandles, boolean[] perUserInstalled,
12936            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12937        final boolean applyUserRestrictions
12938                = (allUserHandles != null) && (perUserInstalled != null);
12939        PackageSetting disabledPs = null;
12940        // Confirm if the system package has been updated
12941        // An updated system app can be deleted. This will also have to restore
12942        // the system pkg from system partition
12943        // reader
12944        synchronized (mPackages) {
12945            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12946        }
12947        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12948                + " disabledPs=" + disabledPs);
12949        if (disabledPs == null) {
12950            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12951            return false;
12952        } else if (DEBUG_REMOVE) {
12953            Slog.d(TAG, "Deleting system pkg from data partition");
12954        }
12955        if (DEBUG_REMOVE) {
12956            if (applyUserRestrictions) {
12957                Slog.d(TAG, "Remembering install states:");
12958                for (int i = 0; i < allUserHandles.length; i++) {
12959                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12960                }
12961            }
12962        }
12963        // Delete the updated package
12964        outInfo.isRemovedPackageSystemUpdate = true;
12965        if (disabledPs.versionCode < newPs.versionCode) {
12966            // Delete data for downgrades
12967            flags &= ~PackageManager.DELETE_KEEP_DATA;
12968        } else {
12969            // Preserve data by setting flag
12970            flags |= PackageManager.DELETE_KEEP_DATA;
12971        }
12972        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12973                allUserHandles, perUserInstalled, outInfo, writeSettings);
12974        if (!ret) {
12975            return false;
12976        }
12977        // writer
12978        synchronized (mPackages) {
12979            // Reinstate the old system package
12980            mSettings.enableSystemPackageLPw(newPs.name);
12981            // Remove any native libraries from the upgraded package.
12982            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12983        }
12984        // Install the system package
12985        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12986        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12987        if (locationIsPrivileged(disabledPs.codePath)) {
12988            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12989        }
12990
12991        final PackageParser.Package newPkg;
12992        try {
12993            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12994        } catch (PackageManagerException e) {
12995            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12996            return false;
12997        }
12998
12999        // writer
13000        synchronized (mPackages) {
13001            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13002
13003            // Propagate the permissions state as we do not want to drop on the floor
13004            // runtime permissions. The update permissions method below will take
13005            // care of removing obsolete permissions and grant install permissions.
13006            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13007            updatePermissionsLPw(newPkg.packageName, newPkg,
13008                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13009
13010            if (applyUserRestrictions) {
13011                if (DEBUG_REMOVE) {
13012                    Slog.d(TAG, "Propagating install state across reinstall");
13013                }
13014                for (int i = 0; i < allUserHandles.length; i++) {
13015                    if (DEBUG_REMOVE) {
13016                        Slog.d(TAG, "    user " + allUserHandles[i]
13017                                + " => " + perUserInstalled[i]);
13018                    }
13019                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13020
13021                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13022                }
13023                // Regardless of writeSettings we need to ensure that this restriction
13024                // state propagation is persisted
13025                mSettings.writeAllUsersPackageRestrictionsLPr();
13026            }
13027            // can downgrade to reader here
13028            if (writeSettings) {
13029                mSettings.writeLPr();
13030            }
13031        }
13032        return true;
13033    }
13034
13035    private boolean deleteInstalledPackageLI(PackageSetting ps,
13036            boolean deleteCodeAndResources, int flags,
13037            int[] allUserHandles, boolean[] perUserInstalled,
13038            PackageRemovedInfo outInfo, boolean writeSettings) {
13039        if (outInfo != null) {
13040            outInfo.uid = ps.appId;
13041        }
13042
13043        // Delete package data from internal structures and also remove data if flag is set
13044        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13045
13046        // Delete application code and resources
13047        if (deleteCodeAndResources && (outInfo != null)) {
13048            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13049                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13050            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13051        }
13052        return true;
13053    }
13054
13055    @Override
13056    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13057            int userId) {
13058        mContext.enforceCallingOrSelfPermission(
13059                android.Manifest.permission.DELETE_PACKAGES, null);
13060        synchronized (mPackages) {
13061            PackageSetting ps = mSettings.mPackages.get(packageName);
13062            if (ps == null) {
13063                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13064                return false;
13065            }
13066            if (!ps.getInstalled(userId)) {
13067                // Can't block uninstall for an app that is not installed or enabled.
13068                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13069                return false;
13070            }
13071            ps.setBlockUninstall(blockUninstall, userId);
13072            mSettings.writePackageRestrictionsLPr(userId);
13073        }
13074        return true;
13075    }
13076
13077    @Override
13078    public boolean getBlockUninstallForUser(String packageName, int userId) {
13079        synchronized (mPackages) {
13080            PackageSetting ps = mSettings.mPackages.get(packageName);
13081            if (ps == null) {
13082                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13083                return false;
13084            }
13085            return ps.getBlockUninstall(userId);
13086        }
13087    }
13088
13089    /*
13090     * This method handles package deletion in general
13091     */
13092    private boolean deletePackageLI(String packageName, UserHandle user,
13093            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13094            int flags, PackageRemovedInfo outInfo,
13095            boolean writeSettings) {
13096        if (packageName == null) {
13097            Slog.w(TAG, "Attempt to delete null packageName.");
13098            return false;
13099        }
13100        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13101        PackageSetting ps;
13102        boolean dataOnly = false;
13103        int removeUser = -1;
13104        int appId = -1;
13105        synchronized (mPackages) {
13106            ps = mSettings.mPackages.get(packageName);
13107            if (ps == null) {
13108                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13109                return false;
13110            }
13111            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13112                    && user.getIdentifier() != UserHandle.USER_ALL) {
13113                // The caller is asking that the package only be deleted for a single
13114                // user.  To do this, we just mark its uninstalled state and delete
13115                // its data.  If this is a system app, we only allow this to happen if
13116                // they have set the special DELETE_SYSTEM_APP which requests different
13117                // semantics than normal for uninstalling system apps.
13118                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13119                final int userId = user.getIdentifier();
13120                ps.setUserState(userId,
13121                        COMPONENT_ENABLED_STATE_DEFAULT,
13122                        false, //installed
13123                        true,  //stopped
13124                        true,  //notLaunched
13125                        false, //hidden
13126                        null, null, null,
13127                        false, // blockUninstall
13128                        ps.readUserState(userId).domainVerificationStatus, 0);
13129                if (!isSystemApp(ps)) {
13130                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13131                        // Other user still have this package installed, so all
13132                        // we need to do is clear this user's data and save that
13133                        // it is uninstalled.
13134                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13135                        removeUser = user.getIdentifier();
13136                        appId = ps.appId;
13137                        scheduleWritePackageRestrictionsLocked(removeUser);
13138                    } else {
13139                        // We need to set it back to 'installed' so the uninstall
13140                        // broadcasts will be sent correctly.
13141                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13142                        ps.setInstalled(true, user.getIdentifier());
13143                    }
13144                } else {
13145                    // This is a system app, so we assume that the
13146                    // other users still have this package installed, so all
13147                    // we need to do is clear this user's data and save that
13148                    // it is uninstalled.
13149                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13150                    removeUser = user.getIdentifier();
13151                    appId = ps.appId;
13152                    scheduleWritePackageRestrictionsLocked(removeUser);
13153                }
13154            }
13155        }
13156
13157        if (removeUser >= 0) {
13158            // From above, we determined that we are deleting this only
13159            // for a single user.  Continue the work here.
13160            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13161            if (outInfo != null) {
13162                outInfo.removedPackage = packageName;
13163                outInfo.removedAppId = appId;
13164                outInfo.removedUsers = new int[] {removeUser};
13165            }
13166            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13167            removeKeystoreDataIfNeeded(removeUser, appId);
13168            schedulePackageCleaning(packageName, removeUser, false);
13169            synchronized (mPackages) {
13170                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13171                    scheduleWritePackageRestrictionsLocked(removeUser);
13172                }
13173                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13174            }
13175            return true;
13176        }
13177
13178        if (dataOnly) {
13179            // Delete application data first
13180            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13181            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13182            return true;
13183        }
13184
13185        boolean ret = false;
13186        if (isSystemApp(ps)) {
13187            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13188            // When an updated system application is deleted we delete the existing resources as well and
13189            // fall back to existing code in system partition
13190            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13191                    flags, outInfo, writeSettings);
13192        } else {
13193            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13194            // Kill application pre-emptively especially for apps on sd.
13195            killApplication(packageName, ps.appId, "uninstall pkg");
13196            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13197                    allUserHandles, perUserInstalled,
13198                    outInfo, writeSettings);
13199        }
13200
13201        return ret;
13202    }
13203
13204    private final class ClearStorageConnection implements ServiceConnection {
13205        IMediaContainerService mContainerService;
13206
13207        @Override
13208        public void onServiceConnected(ComponentName name, IBinder service) {
13209            synchronized (this) {
13210                mContainerService = IMediaContainerService.Stub.asInterface(service);
13211                notifyAll();
13212            }
13213        }
13214
13215        @Override
13216        public void onServiceDisconnected(ComponentName name) {
13217        }
13218    }
13219
13220    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13221        final boolean mounted;
13222        if (Environment.isExternalStorageEmulated()) {
13223            mounted = true;
13224        } else {
13225            final String status = Environment.getExternalStorageState();
13226
13227            mounted = status.equals(Environment.MEDIA_MOUNTED)
13228                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13229        }
13230
13231        if (!mounted) {
13232            return;
13233        }
13234
13235        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13236        int[] users;
13237        if (userId == UserHandle.USER_ALL) {
13238            users = sUserManager.getUserIds();
13239        } else {
13240            users = new int[] { userId };
13241        }
13242        final ClearStorageConnection conn = new ClearStorageConnection();
13243        if (mContext.bindServiceAsUser(
13244                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13245            try {
13246                for (int curUser : users) {
13247                    long timeout = SystemClock.uptimeMillis() + 5000;
13248                    synchronized (conn) {
13249                        long now = SystemClock.uptimeMillis();
13250                        while (conn.mContainerService == null && now < timeout) {
13251                            try {
13252                                conn.wait(timeout - now);
13253                            } catch (InterruptedException e) {
13254                            }
13255                        }
13256                    }
13257                    if (conn.mContainerService == null) {
13258                        return;
13259                    }
13260
13261                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13262                    clearDirectory(conn.mContainerService,
13263                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13264                    if (allData) {
13265                        clearDirectory(conn.mContainerService,
13266                                userEnv.buildExternalStorageAppDataDirs(packageName));
13267                        clearDirectory(conn.mContainerService,
13268                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13269                    }
13270                }
13271            } finally {
13272                mContext.unbindService(conn);
13273            }
13274        }
13275    }
13276
13277    @Override
13278    public void clearApplicationUserData(final String packageName,
13279            final IPackageDataObserver observer, final int userId) {
13280        mContext.enforceCallingOrSelfPermission(
13281                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13282        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13283        // Queue up an async operation since the package deletion may take a little while.
13284        mHandler.post(new Runnable() {
13285            public void run() {
13286                mHandler.removeCallbacks(this);
13287                final boolean succeeded;
13288                synchronized (mInstallLock) {
13289                    succeeded = clearApplicationUserDataLI(packageName, userId);
13290                }
13291                clearExternalStorageDataSync(packageName, userId, true);
13292                if (succeeded) {
13293                    // invoke DeviceStorageMonitor's update method to clear any notifications
13294                    DeviceStorageMonitorInternal
13295                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13296                    if (dsm != null) {
13297                        dsm.checkMemory();
13298                    }
13299                }
13300                if(observer != null) {
13301                    try {
13302                        observer.onRemoveCompleted(packageName, succeeded);
13303                    } catch (RemoteException e) {
13304                        Log.i(TAG, "Observer no longer exists.");
13305                    }
13306                } //end if observer
13307            } //end run
13308        });
13309    }
13310
13311    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13312        if (packageName == null) {
13313            Slog.w(TAG, "Attempt to delete null packageName.");
13314            return false;
13315        }
13316
13317        // Try finding details about the requested package
13318        PackageParser.Package pkg;
13319        synchronized (mPackages) {
13320            pkg = mPackages.get(packageName);
13321            if (pkg == null) {
13322                final PackageSetting ps = mSettings.mPackages.get(packageName);
13323                if (ps != null) {
13324                    pkg = ps.pkg;
13325                }
13326            }
13327
13328            if (pkg == null) {
13329                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13330                return false;
13331            }
13332
13333            PackageSetting ps = (PackageSetting) pkg.mExtras;
13334            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13335        }
13336
13337        // Always delete data directories for package, even if we found no other
13338        // record of app. This helps users recover from UID mismatches without
13339        // resorting to a full data wipe.
13340        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13341        if (retCode < 0) {
13342            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13343            return false;
13344        }
13345
13346        final int appId = pkg.applicationInfo.uid;
13347        removeKeystoreDataIfNeeded(userId, appId);
13348
13349        // Create a native library symlink only if we have native libraries
13350        // and if the native libraries are 32 bit libraries. We do not provide
13351        // this symlink for 64 bit libraries.
13352        if (pkg.applicationInfo.primaryCpuAbi != null &&
13353                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13354            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13355            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13356                    nativeLibPath, userId) < 0) {
13357                Slog.w(TAG, "Failed linking native library dir");
13358                return false;
13359            }
13360        }
13361
13362        return true;
13363    }
13364
13365    /**
13366     * Reverts user permission state changes (permissions and flags) in
13367     * all packages for a given user.
13368     *
13369     * @param userId The device user for which to do a reset.
13370     */
13371    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13372        final int packageCount = mPackages.size();
13373        for (int i = 0; i < packageCount; i++) {
13374            PackageParser.Package pkg = mPackages.valueAt(i);
13375            PackageSetting ps = (PackageSetting) pkg.mExtras;
13376            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13377        }
13378    }
13379
13380    /**
13381     * Reverts user permission state changes (permissions and flags).
13382     *
13383     * @param ps The package for which to reset.
13384     * @param userId The device user for which to do a reset.
13385     */
13386    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13387            final PackageSetting ps, final int userId) {
13388        if (ps.pkg == null) {
13389            return;
13390        }
13391
13392        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13393                | FLAG_PERMISSION_USER_FIXED
13394                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13395
13396        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13397                | FLAG_PERMISSION_POLICY_FIXED;
13398
13399        boolean writeInstallPermissions = false;
13400        boolean writeRuntimePermissions = false;
13401
13402        final int permissionCount = ps.pkg.requestedPermissions.size();
13403        for (int i = 0; i < permissionCount; i++) {
13404            String permission = ps.pkg.requestedPermissions.get(i);
13405
13406            BasePermission bp = mSettings.mPermissions.get(permission);
13407            if (bp == null) {
13408                continue;
13409            }
13410
13411            // If shared user we just reset the state to which only this app contributed.
13412            if (ps.sharedUser != null) {
13413                boolean used = false;
13414                final int packageCount = ps.sharedUser.packages.size();
13415                for (int j = 0; j < packageCount; j++) {
13416                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13417                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13418                            && pkg.pkg.requestedPermissions.contains(permission)) {
13419                        used = true;
13420                        break;
13421                    }
13422                }
13423                if (used) {
13424                    continue;
13425                }
13426            }
13427
13428            PermissionsState permissionsState = ps.getPermissionsState();
13429
13430            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13431
13432            // Always clear the user settable flags.
13433            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13434                    bp.name) != null;
13435            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13436                if (hasInstallState) {
13437                    writeInstallPermissions = true;
13438                } else {
13439                    writeRuntimePermissions = true;
13440                }
13441            }
13442
13443            // Below is only runtime permission handling.
13444            if (!bp.isRuntime()) {
13445                continue;
13446            }
13447
13448            // Never clobber system or policy.
13449            if ((oldFlags & policyOrSystemFlags) != 0) {
13450                continue;
13451            }
13452
13453            // If this permission was granted by default, make sure it is.
13454            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13455                if (permissionsState.grantRuntimePermission(bp, userId)
13456                        != PERMISSION_OPERATION_FAILURE) {
13457                    writeRuntimePermissions = true;
13458                }
13459            } else {
13460                // Otherwise, reset the permission.
13461                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13462                switch (revokeResult) {
13463                    case PERMISSION_OPERATION_SUCCESS: {
13464                        writeRuntimePermissions = true;
13465                    } break;
13466
13467                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13468                        writeRuntimePermissions = true;
13469                        final int appId = ps.appId;
13470                        mHandler.post(new Runnable() {
13471                            @Override
13472                            public void run() {
13473                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13474                            }
13475                        });
13476                    } break;
13477                }
13478            }
13479        }
13480
13481        // Synchronously write as we are taking permissions away.
13482        if (writeRuntimePermissions) {
13483            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13484        }
13485
13486        // Synchronously write as we are taking permissions away.
13487        if (writeInstallPermissions) {
13488            mSettings.writeLPr();
13489        }
13490    }
13491
13492    /**
13493     * Remove entries from the keystore daemon. Will only remove it if the
13494     * {@code appId} is valid.
13495     */
13496    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13497        if (appId < 0) {
13498            return;
13499        }
13500
13501        final KeyStore keyStore = KeyStore.getInstance();
13502        if (keyStore != null) {
13503            if (userId == UserHandle.USER_ALL) {
13504                for (final int individual : sUserManager.getUserIds()) {
13505                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13506                }
13507            } else {
13508                keyStore.clearUid(UserHandle.getUid(userId, appId));
13509            }
13510        } else {
13511            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13512        }
13513    }
13514
13515    @Override
13516    public void deleteApplicationCacheFiles(final String packageName,
13517            final IPackageDataObserver observer) {
13518        mContext.enforceCallingOrSelfPermission(
13519                android.Manifest.permission.DELETE_CACHE_FILES, null);
13520        // Queue up an async operation since the package deletion may take a little while.
13521        final int userId = UserHandle.getCallingUserId();
13522        mHandler.post(new Runnable() {
13523            public void run() {
13524                mHandler.removeCallbacks(this);
13525                final boolean succeded;
13526                synchronized (mInstallLock) {
13527                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13528                }
13529                clearExternalStorageDataSync(packageName, userId, false);
13530                if (observer != null) {
13531                    try {
13532                        observer.onRemoveCompleted(packageName, succeded);
13533                    } catch (RemoteException e) {
13534                        Log.i(TAG, "Observer no longer exists.");
13535                    }
13536                } //end if observer
13537            } //end run
13538        });
13539    }
13540
13541    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13542        if (packageName == null) {
13543            Slog.w(TAG, "Attempt to delete null packageName.");
13544            return false;
13545        }
13546        PackageParser.Package p;
13547        synchronized (mPackages) {
13548            p = mPackages.get(packageName);
13549        }
13550        if (p == null) {
13551            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13552            return false;
13553        }
13554        final ApplicationInfo applicationInfo = p.applicationInfo;
13555        if (applicationInfo == null) {
13556            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13557            return false;
13558        }
13559        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13560        if (retCode < 0) {
13561            Slog.w(TAG, "Couldn't remove cache files for package: "
13562                       + packageName + " u" + userId);
13563            return false;
13564        }
13565        return true;
13566    }
13567
13568    @Override
13569    public void getPackageSizeInfo(final String packageName, int userHandle,
13570            final IPackageStatsObserver observer) {
13571        mContext.enforceCallingOrSelfPermission(
13572                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13573        if (packageName == null) {
13574            throw new IllegalArgumentException("Attempt to get size of null packageName");
13575        }
13576
13577        PackageStats stats = new PackageStats(packageName, userHandle);
13578
13579        /*
13580         * Queue up an async operation since the package measurement may take a
13581         * little while.
13582         */
13583        Message msg = mHandler.obtainMessage(INIT_COPY);
13584        msg.obj = new MeasureParams(stats, observer);
13585        mHandler.sendMessage(msg);
13586    }
13587
13588    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13589            PackageStats pStats) {
13590        if (packageName == null) {
13591            Slog.w(TAG, "Attempt to get size of null packageName.");
13592            return false;
13593        }
13594        PackageParser.Package p;
13595        boolean dataOnly = false;
13596        String libDirRoot = null;
13597        String asecPath = null;
13598        PackageSetting ps = null;
13599        synchronized (mPackages) {
13600            p = mPackages.get(packageName);
13601            ps = mSettings.mPackages.get(packageName);
13602            if(p == null) {
13603                dataOnly = true;
13604                if((ps == null) || (ps.pkg == null)) {
13605                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13606                    return false;
13607                }
13608                p = ps.pkg;
13609            }
13610            if (ps != null) {
13611                libDirRoot = ps.legacyNativeLibraryPathString;
13612            }
13613            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13614                final long token = Binder.clearCallingIdentity();
13615                try {
13616                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13617                    if (secureContainerId != null) {
13618                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13619                    }
13620                } finally {
13621                    Binder.restoreCallingIdentity(token);
13622                }
13623            }
13624        }
13625        String publicSrcDir = null;
13626        if(!dataOnly) {
13627            final ApplicationInfo applicationInfo = p.applicationInfo;
13628            if (applicationInfo == null) {
13629                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13630                return false;
13631            }
13632            if (p.isForwardLocked()) {
13633                publicSrcDir = applicationInfo.getBaseResourcePath();
13634            }
13635        }
13636        // TODO: extend to measure size of split APKs
13637        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13638        // not just the first level.
13639        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13640        // just the primary.
13641        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13642
13643        String apkPath;
13644        File packageDir = new File(p.codePath);
13645
13646        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13647            apkPath = packageDir.getAbsolutePath();
13648            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13649            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13650                libDirRoot = null;
13651            }
13652        } else {
13653            apkPath = p.baseCodePath;
13654        }
13655
13656        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13657                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13658        if (res < 0) {
13659            return false;
13660        }
13661
13662        // Fix-up for forward-locked applications in ASEC containers.
13663        if (!isExternal(p)) {
13664            pStats.codeSize += pStats.externalCodeSize;
13665            pStats.externalCodeSize = 0L;
13666        }
13667
13668        return true;
13669    }
13670
13671
13672    @Override
13673    public void addPackageToPreferred(String packageName) {
13674        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13675    }
13676
13677    @Override
13678    public void removePackageFromPreferred(String packageName) {
13679        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13680    }
13681
13682    @Override
13683    public List<PackageInfo> getPreferredPackages(int flags) {
13684        return new ArrayList<PackageInfo>();
13685    }
13686
13687    private int getUidTargetSdkVersionLockedLPr(int uid) {
13688        Object obj = mSettings.getUserIdLPr(uid);
13689        if (obj instanceof SharedUserSetting) {
13690            final SharedUserSetting sus = (SharedUserSetting) obj;
13691            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13692            final Iterator<PackageSetting> it = sus.packages.iterator();
13693            while (it.hasNext()) {
13694                final PackageSetting ps = it.next();
13695                if (ps.pkg != null) {
13696                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13697                    if (v < vers) vers = v;
13698                }
13699            }
13700            return vers;
13701        } else if (obj instanceof PackageSetting) {
13702            final PackageSetting ps = (PackageSetting) obj;
13703            if (ps.pkg != null) {
13704                return ps.pkg.applicationInfo.targetSdkVersion;
13705            }
13706        }
13707        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13708    }
13709
13710    @Override
13711    public void addPreferredActivity(IntentFilter filter, int match,
13712            ComponentName[] set, ComponentName activity, int userId) {
13713        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13714                "Adding preferred");
13715    }
13716
13717    private void addPreferredActivityInternal(IntentFilter filter, int match,
13718            ComponentName[] set, ComponentName activity, boolean always, int userId,
13719            String opname) {
13720        // writer
13721        int callingUid = Binder.getCallingUid();
13722        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13723        if (filter.countActions() == 0) {
13724            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13725            return;
13726        }
13727        synchronized (mPackages) {
13728            if (mContext.checkCallingOrSelfPermission(
13729                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13730                    != PackageManager.PERMISSION_GRANTED) {
13731                if (getUidTargetSdkVersionLockedLPr(callingUid)
13732                        < Build.VERSION_CODES.FROYO) {
13733                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13734                            + callingUid);
13735                    return;
13736                }
13737                mContext.enforceCallingOrSelfPermission(
13738                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13739            }
13740
13741            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13742            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13743                    + userId + ":");
13744            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13745            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13746            scheduleWritePackageRestrictionsLocked(userId);
13747        }
13748    }
13749
13750    @Override
13751    public void replacePreferredActivity(IntentFilter filter, int match,
13752            ComponentName[] set, ComponentName activity, int userId) {
13753        if (filter.countActions() != 1) {
13754            throw new IllegalArgumentException(
13755                    "replacePreferredActivity expects filter to have only 1 action.");
13756        }
13757        if (filter.countDataAuthorities() != 0
13758                || filter.countDataPaths() != 0
13759                || filter.countDataSchemes() > 1
13760                || filter.countDataTypes() != 0) {
13761            throw new IllegalArgumentException(
13762                    "replacePreferredActivity expects filter to have no data authorities, " +
13763                    "paths, or types; and at most one scheme.");
13764        }
13765
13766        final int callingUid = Binder.getCallingUid();
13767        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13768        synchronized (mPackages) {
13769            if (mContext.checkCallingOrSelfPermission(
13770                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13771                    != PackageManager.PERMISSION_GRANTED) {
13772                if (getUidTargetSdkVersionLockedLPr(callingUid)
13773                        < Build.VERSION_CODES.FROYO) {
13774                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13775                            + Binder.getCallingUid());
13776                    return;
13777                }
13778                mContext.enforceCallingOrSelfPermission(
13779                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13780            }
13781
13782            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13783            if (pir != null) {
13784                // Get all of the existing entries that exactly match this filter.
13785                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13786                if (existing != null && existing.size() == 1) {
13787                    PreferredActivity cur = existing.get(0);
13788                    if (DEBUG_PREFERRED) {
13789                        Slog.i(TAG, "Checking replace of preferred:");
13790                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13791                        if (!cur.mPref.mAlways) {
13792                            Slog.i(TAG, "  -- CUR; not mAlways!");
13793                        } else {
13794                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13795                            Slog.i(TAG, "  -- CUR: mSet="
13796                                    + Arrays.toString(cur.mPref.mSetComponents));
13797                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13798                            Slog.i(TAG, "  -- NEW: mMatch="
13799                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13800                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13801                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13802                        }
13803                    }
13804                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13805                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13806                            && cur.mPref.sameSet(set)) {
13807                        // Setting the preferred activity to what it happens to be already
13808                        if (DEBUG_PREFERRED) {
13809                            Slog.i(TAG, "Replacing with same preferred activity "
13810                                    + cur.mPref.mShortComponent + " for user "
13811                                    + userId + ":");
13812                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13813                        }
13814                        return;
13815                    }
13816                }
13817
13818                if (existing != null) {
13819                    if (DEBUG_PREFERRED) {
13820                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13821                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13822                    }
13823                    for (int i = 0; i < existing.size(); i++) {
13824                        PreferredActivity pa = existing.get(i);
13825                        if (DEBUG_PREFERRED) {
13826                            Slog.i(TAG, "Removing existing preferred activity "
13827                                    + pa.mPref.mComponent + ":");
13828                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13829                        }
13830                        pir.removeFilter(pa);
13831                    }
13832                }
13833            }
13834            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13835                    "Replacing preferred");
13836        }
13837    }
13838
13839    @Override
13840    public void clearPackagePreferredActivities(String packageName) {
13841        final int uid = Binder.getCallingUid();
13842        // writer
13843        synchronized (mPackages) {
13844            PackageParser.Package pkg = mPackages.get(packageName);
13845            if (pkg == null || pkg.applicationInfo.uid != uid) {
13846                if (mContext.checkCallingOrSelfPermission(
13847                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13848                        != PackageManager.PERMISSION_GRANTED) {
13849                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13850                            < Build.VERSION_CODES.FROYO) {
13851                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13852                                + Binder.getCallingUid());
13853                        return;
13854                    }
13855                    mContext.enforceCallingOrSelfPermission(
13856                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13857                }
13858            }
13859
13860            int user = UserHandle.getCallingUserId();
13861            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13862                scheduleWritePackageRestrictionsLocked(user);
13863            }
13864        }
13865    }
13866
13867    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13868    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13869        ArrayList<PreferredActivity> removed = null;
13870        boolean changed = false;
13871        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13872            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13873            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13874            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13875                continue;
13876            }
13877            Iterator<PreferredActivity> it = pir.filterIterator();
13878            while (it.hasNext()) {
13879                PreferredActivity pa = it.next();
13880                // Mark entry for removal only if it matches the package name
13881                // and the entry is of type "always".
13882                if (packageName == null ||
13883                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13884                                && pa.mPref.mAlways)) {
13885                    if (removed == null) {
13886                        removed = new ArrayList<PreferredActivity>();
13887                    }
13888                    removed.add(pa);
13889                }
13890            }
13891            if (removed != null) {
13892                for (int j=0; j<removed.size(); j++) {
13893                    PreferredActivity pa = removed.get(j);
13894                    pir.removeFilter(pa);
13895                }
13896                changed = true;
13897            }
13898        }
13899        return changed;
13900    }
13901
13902    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13903    private void clearIntentFilterVerificationsLPw(int userId) {
13904        final int packageCount = mPackages.size();
13905        for (int i = 0; i < packageCount; i++) {
13906            PackageParser.Package pkg = mPackages.valueAt(i);
13907            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13908        }
13909    }
13910
13911    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13912    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13913        if (userId == UserHandle.USER_ALL) {
13914            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13915                    sUserManager.getUserIds())) {
13916                for (int oneUserId : sUserManager.getUserIds()) {
13917                    scheduleWritePackageRestrictionsLocked(oneUserId);
13918                }
13919            }
13920        } else {
13921            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13922                scheduleWritePackageRestrictionsLocked(userId);
13923            }
13924        }
13925    }
13926
13927    void clearDefaultBrowserIfNeeded(String packageName) {
13928        for (int oneUserId : sUserManager.getUserIds()) {
13929            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13930            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13931            if (packageName.equals(defaultBrowserPackageName)) {
13932                setDefaultBrowserPackageName(null, oneUserId);
13933            }
13934        }
13935    }
13936
13937    @Override
13938    public void resetApplicationPreferences(int userId) {
13939        mContext.enforceCallingOrSelfPermission(
13940                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13941        // writer
13942        synchronized (mPackages) {
13943            final long identity = Binder.clearCallingIdentity();
13944            try {
13945                clearPackagePreferredActivitiesLPw(null, userId);
13946                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13947                // TODO: We have to reset the default SMS and Phone. This requires
13948                // significant refactoring to keep all default apps in the package
13949                // manager (cleaner but more work) or have the services provide
13950                // callbacks to the package manager to request a default app reset.
13951                applyFactoryDefaultBrowserLPw(userId);
13952                clearIntentFilterVerificationsLPw(userId);
13953                primeDomainVerificationsLPw(userId);
13954                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13955                scheduleWritePackageRestrictionsLocked(userId);
13956            } finally {
13957                Binder.restoreCallingIdentity(identity);
13958            }
13959        }
13960    }
13961
13962    @Override
13963    public int getPreferredActivities(List<IntentFilter> outFilters,
13964            List<ComponentName> outActivities, String packageName) {
13965
13966        int num = 0;
13967        final int userId = UserHandle.getCallingUserId();
13968        // reader
13969        synchronized (mPackages) {
13970            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13971            if (pir != null) {
13972                final Iterator<PreferredActivity> it = pir.filterIterator();
13973                while (it.hasNext()) {
13974                    final PreferredActivity pa = it.next();
13975                    if (packageName == null
13976                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13977                                    && pa.mPref.mAlways)) {
13978                        if (outFilters != null) {
13979                            outFilters.add(new IntentFilter(pa));
13980                        }
13981                        if (outActivities != null) {
13982                            outActivities.add(pa.mPref.mComponent);
13983                        }
13984                    }
13985                }
13986            }
13987        }
13988
13989        return num;
13990    }
13991
13992    @Override
13993    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13994            int userId) {
13995        int callingUid = Binder.getCallingUid();
13996        if (callingUid != Process.SYSTEM_UID) {
13997            throw new SecurityException(
13998                    "addPersistentPreferredActivity can only be run by the system");
13999        }
14000        if (filter.countActions() == 0) {
14001            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14002            return;
14003        }
14004        synchronized (mPackages) {
14005            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14006                    " :");
14007            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14008            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14009                    new PersistentPreferredActivity(filter, activity));
14010            scheduleWritePackageRestrictionsLocked(userId);
14011        }
14012    }
14013
14014    @Override
14015    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14016        int callingUid = Binder.getCallingUid();
14017        if (callingUid != Process.SYSTEM_UID) {
14018            throw new SecurityException(
14019                    "clearPackagePersistentPreferredActivities can only be run by the system");
14020        }
14021        ArrayList<PersistentPreferredActivity> removed = null;
14022        boolean changed = false;
14023        synchronized (mPackages) {
14024            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14025                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14026                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14027                        .valueAt(i);
14028                if (userId != thisUserId) {
14029                    continue;
14030                }
14031                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14032                while (it.hasNext()) {
14033                    PersistentPreferredActivity ppa = it.next();
14034                    // Mark entry for removal only if it matches the package name.
14035                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14036                        if (removed == null) {
14037                            removed = new ArrayList<PersistentPreferredActivity>();
14038                        }
14039                        removed.add(ppa);
14040                    }
14041                }
14042                if (removed != null) {
14043                    for (int j=0; j<removed.size(); j++) {
14044                        PersistentPreferredActivity ppa = removed.get(j);
14045                        ppir.removeFilter(ppa);
14046                    }
14047                    changed = true;
14048                }
14049            }
14050
14051            if (changed) {
14052                scheduleWritePackageRestrictionsLocked(userId);
14053            }
14054        }
14055    }
14056
14057    /**
14058     * Common machinery for picking apart a restored XML blob and passing
14059     * it to a caller-supplied functor to be applied to the running system.
14060     */
14061    private void restoreFromXml(XmlPullParser parser, int userId,
14062            String expectedStartTag, BlobXmlRestorer functor)
14063            throws IOException, XmlPullParserException {
14064        int type;
14065        while ((type = parser.next()) != XmlPullParser.START_TAG
14066                && type != XmlPullParser.END_DOCUMENT) {
14067        }
14068        if (type != XmlPullParser.START_TAG) {
14069            // oops didn't find a start tag?!
14070            if (DEBUG_BACKUP) {
14071                Slog.e(TAG, "Didn't find start tag during restore");
14072            }
14073            return;
14074        }
14075
14076        // this is supposed to be TAG_PREFERRED_BACKUP
14077        if (!expectedStartTag.equals(parser.getName())) {
14078            if (DEBUG_BACKUP) {
14079                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14080            }
14081            return;
14082        }
14083
14084        // skip interfering stuff, then we're aligned with the backing implementation
14085        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14086        functor.apply(parser, userId);
14087    }
14088
14089    private interface BlobXmlRestorer {
14090        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14091    }
14092
14093    /**
14094     * Non-Binder method, support for the backup/restore mechanism: write the
14095     * full set of preferred activities in its canonical XML format.  Returns the
14096     * XML output as a byte array, or null if there is none.
14097     */
14098    @Override
14099    public byte[] getPreferredActivityBackup(int userId) {
14100        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14101            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14102        }
14103
14104        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14105        try {
14106            final XmlSerializer serializer = new FastXmlSerializer();
14107            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14108            serializer.startDocument(null, true);
14109            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14110
14111            synchronized (mPackages) {
14112                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14113            }
14114
14115            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14116            serializer.endDocument();
14117            serializer.flush();
14118        } catch (Exception e) {
14119            if (DEBUG_BACKUP) {
14120                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14121            }
14122            return null;
14123        }
14124
14125        return dataStream.toByteArray();
14126    }
14127
14128    @Override
14129    public void restorePreferredActivities(byte[] backup, int userId) {
14130        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14131            throw new SecurityException("Only the system may call restorePreferredActivities()");
14132        }
14133
14134        try {
14135            final XmlPullParser parser = Xml.newPullParser();
14136            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14137            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14138                    new BlobXmlRestorer() {
14139                        @Override
14140                        public void apply(XmlPullParser parser, int userId)
14141                                throws XmlPullParserException, IOException {
14142                            synchronized (mPackages) {
14143                                mSettings.readPreferredActivitiesLPw(parser, userId);
14144                            }
14145                        }
14146                    } );
14147        } catch (Exception e) {
14148            if (DEBUG_BACKUP) {
14149                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14150            }
14151        }
14152    }
14153
14154    /**
14155     * Non-Binder method, support for the backup/restore mechanism: write the
14156     * default browser (etc) settings in its canonical XML format.  Returns the default
14157     * browser XML representation as a byte array, or null if there is none.
14158     */
14159    @Override
14160    public byte[] getDefaultAppsBackup(int userId) {
14161        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14162            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14163        }
14164
14165        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14166        try {
14167            final XmlSerializer serializer = new FastXmlSerializer();
14168            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14169            serializer.startDocument(null, true);
14170            serializer.startTag(null, TAG_DEFAULT_APPS);
14171
14172            synchronized (mPackages) {
14173                mSettings.writeDefaultAppsLPr(serializer, userId);
14174            }
14175
14176            serializer.endTag(null, TAG_DEFAULT_APPS);
14177            serializer.endDocument();
14178            serializer.flush();
14179        } catch (Exception e) {
14180            if (DEBUG_BACKUP) {
14181                Slog.e(TAG, "Unable to write default apps for backup", e);
14182            }
14183            return null;
14184        }
14185
14186        return dataStream.toByteArray();
14187    }
14188
14189    @Override
14190    public void restoreDefaultApps(byte[] backup, int userId) {
14191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14192            throw new SecurityException("Only the system may call restoreDefaultApps()");
14193        }
14194
14195        try {
14196            final XmlPullParser parser = Xml.newPullParser();
14197            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14198            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14199                    new BlobXmlRestorer() {
14200                        @Override
14201                        public void apply(XmlPullParser parser, int userId)
14202                                throws XmlPullParserException, IOException {
14203                            synchronized (mPackages) {
14204                                mSettings.readDefaultAppsLPw(parser, userId);
14205                            }
14206                        }
14207                    } );
14208        } catch (Exception e) {
14209            if (DEBUG_BACKUP) {
14210                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14211            }
14212        }
14213    }
14214
14215    @Override
14216    public byte[] getIntentFilterVerificationBackup(int userId) {
14217        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14218            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14219        }
14220
14221        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14222        try {
14223            final XmlSerializer serializer = new FastXmlSerializer();
14224            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14225            serializer.startDocument(null, true);
14226            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14227
14228            synchronized (mPackages) {
14229                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14230            }
14231
14232            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14233            serializer.endDocument();
14234            serializer.flush();
14235        } catch (Exception e) {
14236            if (DEBUG_BACKUP) {
14237                Slog.e(TAG, "Unable to write default apps for backup", e);
14238            }
14239            return null;
14240        }
14241
14242        return dataStream.toByteArray();
14243    }
14244
14245    @Override
14246    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14247        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14248            throw new SecurityException("Only the system may call restorePreferredActivities()");
14249        }
14250
14251        try {
14252            final XmlPullParser parser = Xml.newPullParser();
14253            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14254            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14255                    new BlobXmlRestorer() {
14256                        @Override
14257                        public void apply(XmlPullParser parser, int userId)
14258                                throws XmlPullParserException, IOException {
14259                            synchronized (mPackages) {
14260                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14261                                mSettings.writeLPr();
14262                            }
14263                        }
14264                    } );
14265        } catch (Exception e) {
14266            if (DEBUG_BACKUP) {
14267                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14268            }
14269        }
14270    }
14271
14272    @Override
14273    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14274            int sourceUserId, int targetUserId, int flags) {
14275        mContext.enforceCallingOrSelfPermission(
14276                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14277        int callingUid = Binder.getCallingUid();
14278        enforceOwnerRights(ownerPackage, callingUid);
14279        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14280        if (intentFilter.countActions() == 0) {
14281            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14282            return;
14283        }
14284        synchronized (mPackages) {
14285            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14286                    ownerPackage, targetUserId, flags);
14287            CrossProfileIntentResolver resolver =
14288                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14289            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14290            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14291            if (existing != null) {
14292                int size = existing.size();
14293                for (int i = 0; i < size; i++) {
14294                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14295                        return;
14296                    }
14297                }
14298            }
14299            resolver.addFilter(newFilter);
14300            scheduleWritePackageRestrictionsLocked(sourceUserId);
14301        }
14302    }
14303
14304    @Override
14305    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14306        mContext.enforceCallingOrSelfPermission(
14307                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14308        int callingUid = Binder.getCallingUid();
14309        enforceOwnerRights(ownerPackage, callingUid);
14310        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14311        synchronized (mPackages) {
14312            CrossProfileIntentResolver resolver =
14313                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14314            ArraySet<CrossProfileIntentFilter> set =
14315                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14316            for (CrossProfileIntentFilter filter : set) {
14317                if (filter.getOwnerPackage().equals(ownerPackage)) {
14318                    resolver.removeFilter(filter);
14319                }
14320            }
14321            scheduleWritePackageRestrictionsLocked(sourceUserId);
14322        }
14323    }
14324
14325    // Enforcing that callingUid is owning pkg on userId
14326    private void enforceOwnerRights(String pkg, int callingUid) {
14327        // The system owns everything.
14328        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14329            return;
14330        }
14331        int callingUserId = UserHandle.getUserId(callingUid);
14332        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14333        if (pi == null) {
14334            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14335                    + callingUserId);
14336        }
14337        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14338            throw new SecurityException("Calling uid " + callingUid
14339                    + " does not own package " + pkg);
14340        }
14341    }
14342
14343    @Override
14344    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14345        Intent intent = new Intent(Intent.ACTION_MAIN);
14346        intent.addCategory(Intent.CATEGORY_HOME);
14347
14348        final int callingUserId = UserHandle.getCallingUserId();
14349        List<ResolveInfo> list = queryIntentActivities(intent, null,
14350                PackageManager.GET_META_DATA, callingUserId);
14351        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14352                true, false, false, callingUserId);
14353
14354        allHomeCandidates.clear();
14355        if (list != null) {
14356            for (ResolveInfo ri : list) {
14357                allHomeCandidates.add(ri);
14358            }
14359        }
14360        return (preferred == null || preferred.activityInfo == null)
14361                ? null
14362                : new ComponentName(preferred.activityInfo.packageName,
14363                        preferred.activityInfo.name);
14364    }
14365
14366    @Override
14367    public void setApplicationEnabledSetting(String appPackageName,
14368            int newState, int flags, int userId, String callingPackage) {
14369        if (!sUserManager.exists(userId)) return;
14370        if (callingPackage == null) {
14371            callingPackage = Integer.toString(Binder.getCallingUid());
14372        }
14373        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14374    }
14375
14376    @Override
14377    public void setComponentEnabledSetting(ComponentName componentName,
14378            int newState, int flags, int userId) {
14379        if (!sUserManager.exists(userId)) return;
14380        setEnabledSetting(componentName.getPackageName(),
14381                componentName.getClassName(), newState, flags, userId, null);
14382    }
14383
14384    private void setEnabledSetting(final String packageName, String className, int newState,
14385            final int flags, int userId, String callingPackage) {
14386        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14387              || newState == COMPONENT_ENABLED_STATE_ENABLED
14388              || newState == COMPONENT_ENABLED_STATE_DISABLED
14389              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14390              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14391            throw new IllegalArgumentException("Invalid new component state: "
14392                    + newState);
14393        }
14394        PackageSetting pkgSetting;
14395        final int uid = Binder.getCallingUid();
14396        final int permission = mContext.checkCallingOrSelfPermission(
14397                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14398        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14399        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14400        boolean sendNow = false;
14401        boolean isApp = (className == null);
14402        String componentName = isApp ? packageName : className;
14403        int packageUid = -1;
14404        ArrayList<String> components;
14405
14406        // writer
14407        synchronized (mPackages) {
14408            pkgSetting = mSettings.mPackages.get(packageName);
14409            if (pkgSetting == null) {
14410                if (className == null) {
14411                    throw new IllegalArgumentException(
14412                            "Unknown package: " + packageName);
14413                }
14414                throw new IllegalArgumentException(
14415                        "Unknown component: " + packageName
14416                        + "/" + className);
14417            }
14418            // Allow root and verify that userId is not being specified by a different user
14419            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14420                throw new SecurityException(
14421                        "Permission Denial: attempt to change component state from pid="
14422                        + Binder.getCallingPid()
14423                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14424            }
14425            if (className == null) {
14426                // We're dealing with an application/package level state change
14427                if (pkgSetting.getEnabled(userId) == newState) {
14428                    // Nothing to do
14429                    return;
14430                }
14431                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14432                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14433                    // Don't care about who enables an app.
14434                    callingPackage = null;
14435                }
14436                pkgSetting.setEnabled(newState, userId, callingPackage);
14437                // pkgSetting.pkg.mSetEnabled = newState;
14438            } else {
14439                // We're dealing with a component level state change
14440                // First, verify that this is a valid class name.
14441                PackageParser.Package pkg = pkgSetting.pkg;
14442                if (pkg == null || !pkg.hasComponentClassName(className)) {
14443                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14444                        throw new IllegalArgumentException("Component class " + className
14445                                + " does not exist in " + packageName);
14446                    } else {
14447                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14448                                + className + " does not exist in " + packageName);
14449                    }
14450                }
14451                switch (newState) {
14452                case COMPONENT_ENABLED_STATE_ENABLED:
14453                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14454                        return;
14455                    }
14456                    break;
14457                case COMPONENT_ENABLED_STATE_DISABLED:
14458                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14459                        return;
14460                    }
14461                    break;
14462                case COMPONENT_ENABLED_STATE_DEFAULT:
14463                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14464                        return;
14465                    }
14466                    break;
14467                default:
14468                    Slog.e(TAG, "Invalid new component state: " + newState);
14469                    return;
14470                }
14471            }
14472            scheduleWritePackageRestrictionsLocked(userId);
14473            components = mPendingBroadcasts.get(userId, packageName);
14474            final boolean newPackage = components == null;
14475            if (newPackage) {
14476                components = new ArrayList<String>();
14477            }
14478            if (!components.contains(componentName)) {
14479                components.add(componentName);
14480            }
14481            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14482                sendNow = true;
14483                // Purge entry from pending broadcast list if another one exists already
14484                // since we are sending one right away.
14485                mPendingBroadcasts.remove(userId, packageName);
14486            } else {
14487                if (newPackage) {
14488                    mPendingBroadcasts.put(userId, packageName, components);
14489                }
14490                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14491                    // Schedule a message
14492                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14493                }
14494            }
14495        }
14496
14497        long callingId = Binder.clearCallingIdentity();
14498        try {
14499            if (sendNow) {
14500                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14501                sendPackageChangedBroadcast(packageName,
14502                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14503            }
14504        } finally {
14505            Binder.restoreCallingIdentity(callingId);
14506        }
14507    }
14508
14509    private void sendPackageChangedBroadcast(String packageName,
14510            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14511        if (DEBUG_INSTALL)
14512            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14513                    + componentNames);
14514        Bundle extras = new Bundle(4);
14515        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14516        String nameList[] = new String[componentNames.size()];
14517        componentNames.toArray(nameList);
14518        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14519        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14520        extras.putInt(Intent.EXTRA_UID, packageUid);
14521        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14522                new int[] {UserHandle.getUserId(packageUid)});
14523    }
14524
14525    @Override
14526    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14527        if (!sUserManager.exists(userId)) return;
14528        final int uid = Binder.getCallingUid();
14529        final int permission = mContext.checkCallingOrSelfPermission(
14530                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14531        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14532        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14533        // writer
14534        synchronized (mPackages) {
14535            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14536                    allowedByPermission, uid, userId)) {
14537                scheduleWritePackageRestrictionsLocked(userId);
14538            }
14539        }
14540    }
14541
14542    @Override
14543    public String getInstallerPackageName(String packageName) {
14544        // reader
14545        synchronized (mPackages) {
14546            return mSettings.getInstallerPackageNameLPr(packageName);
14547        }
14548    }
14549
14550    @Override
14551    public int getApplicationEnabledSetting(String packageName, int userId) {
14552        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14553        int uid = Binder.getCallingUid();
14554        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14555        // reader
14556        synchronized (mPackages) {
14557            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14558        }
14559    }
14560
14561    @Override
14562    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14563        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14564        int uid = Binder.getCallingUid();
14565        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14566        // reader
14567        synchronized (mPackages) {
14568            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14569        }
14570    }
14571
14572    @Override
14573    public void enterSafeMode() {
14574        enforceSystemOrRoot("Only the system can request entering safe mode");
14575
14576        if (!mSystemReady) {
14577            mSafeMode = true;
14578        }
14579    }
14580
14581    @Override
14582    public void systemReady() {
14583        mSystemReady = true;
14584
14585        // Read the compatibilty setting when the system is ready.
14586        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14587                mContext.getContentResolver(),
14588                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14589        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14590        if (DEBUG_SETTINGS) {
14591            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14592        }
14593
14594        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14595
14596        synchronized (mPackages) {
14597            // Verify that all of the preferred activity components actually
14598            // exist.  It is possible for applications to be updated and at
14599            // that point remove a previously declared activity component that
14600            // had been set as a preferred activity.  We try to clean this up
14601            // the next time we encounter that preferred activity, but it is
14602            // possible for the user flow to never be able to return to that
14603            // situation so here we do a sanity check to make sure we haven't
14604            // left any junk around.
14605            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14606            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14607                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14608                removed.clear();
14609                for (PreferredActivity pa : pir.filterSet()) {
14610                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14611                        removed.add(pa);
14612                    }
14613                }
14614                if (removed.size() > 0) {
14615                    for (int r=0; r<removed.size(); r++) {
14616                        PreferredActivity pa = removed.get(r);
14617                        Slog.w(TAG, "Removing dangling preferred activity: "
14618                                + pa.mPref.mComponent);
14619                        pir.removeFilter(pa);
14620                    }
14621                    mSettings.writePackageRestrictionsLPr(
14622                            mSettings.mPreferredActivities.keyAt(i));
14623                }
14624            }
14625
14626            for (int userId : UserManagerService.getInstance().getUserIds()) {
14627                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14628                    grantPermissionsUserIds = ArrayUtils.appendInt(
14629                            grantPermissionsUserIds, userId);
14630                }
14631            }
14632        }
14633        sUserManager.systemReady();
14634
14635        // If we upgraded grant all default permissions before kicking off.
14636        for (int userId : grantPermissionsUserIds) {
14637            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14638        }
14639
14640        // Kick off any messages waiting for system ready
14641        if (mPostSystemReadyMessages != null) {
14642            for (Message msg : mPostSystemReadyMessages) {
14643                msg.sendToTarget();
14644            }
14645            mPostSystemReadyMessages = null;
14646        }
14647
14648        // Watch for external volumes that come and go over time
14649        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14650        storage.registerListener(mStorageListener);
14651
14652        mInstallerService.systemReady();
14653        mPackageDexOptimizer.systemReady();
14654
14655        MountServiceInternal mountServiceInternal = LocalServices.getService(
14656                MountServiceInternal.class);
14657        mountServiceInternal.addExternalStoragePolicy(
14658                new MountServiceInternal.ExternalStorageMountPolicy() {
14659            @Override
14660            public int getMountMode(int uid, String packageName) {
14661                if (Process.isIsolated(uid)) {
14662                    return Zygote.MOUNT_EXTERNAL_NONE;
14663                }
14664                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14665                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14666                }
14667                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14668                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14669                }
14670                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14671                    return Zygote.MOUNT_EXTERNAL_READ;
14672                }
14673                return Zygote.MOUNT_EXTERNAL_WRITE;
14674            }
14675
14676            @Override
14677            public boolean hasExternalStorage(int uid, String packageName) {
14678                return true;
14679            }
14680        });
14681    }
14682
14683    @Override
14684    public boolean isSafeMode() {
14685        return mSafeMode;
14686    }
14687
14688    @Override
14689    public boolean hasSystemUidErrors() {
14690        return mHasSystemUidErrors;
14691    }
14692
14693    static String arrayToString(int[] array) {
14694        StringBuffer buf = new StringBuffer(128);
14695        buf.append('[');
14696        if (array != null) {
14697            for (int i=0; i<array.length; i++) {
14698                if (i > 0) buf.append(", ");
14699                buf.append(array[i]);
14700            }
14701        }
14702        buf.append(']');
14703        return buf.toString();
14704    }
14705
14706    static class DumpState {
14707        public static final int DUMP_LIBS = 1 << 0;
14708        public static final int DUMP_FEATURES = 1 << 1;
14709        public static final int DUMP_RESOLVERS = 1 << 2;
14710        public static final int DUMP_PERMISSIONS = 1 << 3;
14711        public static final int DUMP_PACKAGES = 1 << 4;
14712        public static final int DUMP_SHARED_USERS = 1 << 5;
14713        public static final int DUMP_MESSAGES = 1 << 6;
14714        public static final int DUMP_PROVIDERS = 1 << 7;
14715        public static final int DUMP_VERIFIERS = 1 << 8;
14716        public static final int DUMP_PREFERRED = 1 << 9;
14717        public static final int DUMP_PREFERRED_XML = 1 << 10;
14718        public static final int DUMP_KEYSETS = 1 << 11;
14719        public static final int DUMP_VERSION = 1 << 12;
14720        public static final int DUMP_INSTALLS = 1 << 13;
14721        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14722        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14723
14724        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14725
14726        private int mTypes;
14727
14728        private int mOptions;
14729
14730        private boolean mTitlePrinted;
14731
14732        private SharedUserSetting mSharedUser;
14733
14734        public boolean isDumping(int type) {
14735            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14736                return true;
14737            }
14738
14739            return (mTypes & type) != 0;
14740        }
14741
14742        public void setDump(int type) {
14743            mTypes |= type;
14744        }
14745
14746        public boolean isOptionEnabled(int option) {
14747            return (mOptions & option) != 0;
14748        }
14749
14750        public void setOptionEnabled(int option) {
14751            mOptions |= option;
14752        }
14753
14754        public boolean onTitlePrinted() {
14755            final boolean printed = mTitlePrinted;
14756            mTitlePrinted = true;
14757            return printed;
14758        }
14759
14760        public boolean getTitlePrinted() {
14761            return mTitlePrinted;
14762        }
14763
14764        public void setTitlePrinted(boolean enabled) {
14765            mTitlePrinted = enabled;
14766        }
14767
14768        public SharedUserSetting getSharedUser() {
14769            return mSharedUser;
14770        }
14771
14772        public void setSharedUser(SharedUserSetting user) {
14773            mSharedUser = user;
14774        }
14775    }
14776
14777    @Override
14778    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14779        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14780                != PackageManager.PERMISSION_GRANTED) {
14781            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14782                    + Binder.getCallingPid()
14783                    + ", uid=" + Binder.getCallingUid()
14784                    + " without permission "
14785                    + android.Manifest.permission.DUMP);
14786            return;
14787        }
14788
14789        DumpState dumpState = new DumpState();
14790        boolean fullPreferred = false;
14791        boolean checkin = false;
14792
14793        String packageName = null;
14794        ArraySet<String> permissionNames = null;
14795
14796        int opti = 0;
14797        while (opti < args.length) {
14798            String opt = args[opti];
14799            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14800                break;
14801            }
14802            opti++;
14803
14804            if ("-a".equals(opt)) {
14805                // Right now we only know how to print all.
14806            } else if ("-h".equals(opt)) {
14807                pw.println("Package manager dump options:");
14808                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14809                pw.println("    --checkin: dump for a checkin");
14810                pw.println("    -f: print details of intent filters");
14811                pw.println("    -h: print this help");
14812                pw.println("  cmd may be one of:");
14813                pw.println("    l[ibraries]: list known shared libraries");
14814                pw.println("    f[ibraries]: list device features");
14815                pw.println("    k[eysets]: print known keysets");
14816                pw.println("    r[esolvers]: dump intent resolvers");
14817                pw.println("    perm[issions]: dump permissions");
14818                pw.println("    permission [name ...]: dump declaration and use of given permission");
14819                pw.println("    pref[erred]: print preferred package settings");
14820                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14821                pw.println("    prov[iders]: dump content providers");
14822                pw.println("    p[ackages]: dump installed packages");
14823                pw.println("    s[hared-users]: dump shared user IDs");
14824                pw.println("    m[essages]: print collected runtime messages");
14825                pw.println("    v[erifiers]: print package verifier info");
14826                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14827                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14828                pw.println("    version: print database version info");
14829                pw.println("    write: write current settings now");
14830                pw.println("    installs: details about install sessions");
14831                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14832                pw.println("    <package.name>: info about given package");
14833                return;
14834            } else if ("--checkin".equals(opt)) {
14835                checkin = true;
14836            } else if ("-f".equals(opt)) {
14837                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14838            } else {
14839                pw.println("Unknown argument: " + opt + "; use -h for help");
14840            }
14841        }
14842
14843        // Is the caller requesting to dump a particular piece of data?
14844        if (opti < args.length) {
14845            String cmd = args[opti];
14846            opti++;
14847            // Is this a package name?
14848            if ("android".equals(cmd) || cmd.contains(".")) {
14849                packageName = cmd;
14850                // When dumping a single package, we always dump all of its
14851                // filter information since the amount of data will be reasonable.
14852                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14853            } else if ("check-permission".equals(cmd)) {
14854                if (opti >= args.length) {
14855                    pw.println("Error: check-permission missing permission argument");
14856                    return;
14857                }
14858                String perm = args[opti];
14859                opti++;
14860                if (opti >= args.length) {
14861                    pw.println("Error: check-permission missing package argument");
14862                    return;
14863                }
14864                String pkg = args[opti];
14865                opti++;
14866                int user = UserHandle.getUserId(Binder.getCallingUid());
14867                if (opti < args.length) {
14868                    try {
14869                        user = Integer.parseInt(args[opti]);
14870                    } catch (NumberFormatException e) {
14871                        pw.println("Error: check-permission user argument is not a number: "
14872                                + args[opti]);
14873                        return;
14874                    }
14875                }
14876                pw.println(checkPermission(perm, pkg, user));
14877                return;
14878            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14879                dumpState.setDump(DumpState.DUMP_LIBS);
14880            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14881                dumpState.setDump(DumpState.DUMP_FEATURES);
14882            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14883                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14884            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14885                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14886            } else if ("permission".equals(cmd)) {
14887                if (opti >= args.length) {
14888                    pw.println("Error: permission requires permission name");
14889                    return;
14890                }
14891                permissionNames = new ArraySet<>();
14892                while (opti < args.length) {
14893                    permissionNames.add(args[opti]);
14894                    opti++;
14895                }
14896                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14897                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14898            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14899                dumpState.setDump(DumpState.DUMP_PREFERRED);
14900            } else if ("preferred-xml".equals(cmd)) {
14901                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14902                if (opti < args.length && "--full".equals(args[opti])) {
14903                    fullPreferred = true;
14904                    opti++;
14905                }
14906            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14907                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14908            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14909                dumpState.setDump(DumpState.DUMP_PACKAGES);
14910            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14911                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14912            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14913                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14914            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14915                dumpState.setDump(DumpState.DUMP_MESSAGES);
14916            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14917                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14918            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14919                    || "intent-filter-verifiers".equals(cmd)) {
14920                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14921            } else if ("version".equals(cmd)) {
14922                dumpState.setDump(DumpState.DUMP_VERSION);
14923            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14924                dumpState.setDump(DumpState.DUMP_KEYSETS);
14925            } else if ("installs".equals(cmd)) {
14926                dumpState.setDump(DumpState.DUMP_INSTALLS);
14927            } else if ("write".equals(cmd)) {
14928                synchronized (mPackages) {
14929                    mSettings.writeLPr();
14930                    pw.println("Settings written.");
14931                    return;
14932                }
14933            }
14934        }
14935
14936        if (checkin) {
14937            pw.println("vers,1");
14938        }
14939
14940        // reader
14941        synchronized (mPackages) {
14942            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14943                if (!checkin) {
14944                    if (dumpState.onTitlePrinted())
14945                        pw.println();
14946                    pw.println("Database versions:");
14947                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14948                }
14949            }
14950
14951            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14952                if (!checkin) {
14953                    if (dumpState.onTitlePrinted())
14954                        pw.println();
14955                    pw.println("Verifiers:");
14956                    pw.print("  Required: ");
14957                    pw.print(mRequiredVerifierPackage);
14958                    pw.print(" (uid=");
14959                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14960                    pw.println(")");
14961                } else if (mRequiredVerifierPackage != null) {
14962                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14963                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14964                }
14965            }
14966
14967            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14968                    packageName == null) {
14969                if (mIntentFilterVerifierComponent != null) {
14970                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14971                    if (!checkin) {
14972                        if (dumpState.onTitlePrinted())
14973                            pw.println();
14974                        pw.println("Intent Filter Verifier:");
14975                        pw.print("  Using: ");
14976                        pw.print(verifierPackageName);
14977                        pw.print(" (uid=");
14978                        pw.print(getPackageUid(verifierPackageName, 0));
14979                        pw.println(")");
14980                    } else if (verifierPackageName != null) {
14981                        pw.print("ifv,"); pw.print(verifierPackageName);
14982                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14983                    }
14984                } else {
14985                    pw.println();
14986                    pw.println("No Intent Filter Verifier available!");
14987                }
14988            }
14989
14990            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14991                boolean printedHeader = false;
14992                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14993                while (it.hasNext()) {
14994                    String name = it.next();
14995                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14996                    if (!checkin) {
14997                        if (!printedHeader) {
14998                            if (dumpState.onTitlePrinted())
14999                                pw.println();
15000                            pw.println("Libraries:");
15001                            printedHeader = true;
15002                        }
15003                        pw.print("  ");
15004                    } else {
15005                        pw.print("lib,");
15006                    }
15007                    pw.print(name);
15008                    if (!checkin) {
15009                        pw.print(" -> ");
15010                    }
15011                    if (ent.path != null) {
15012                        if (!checkin) {
15013                            pw.print("(jar) ");
15014                            pw.print(ent.path);
15015                        } else {
15016                            pw.print(",jar,");
15017                            pw.print(ent.path);
15018                        }
15019                    } else {
15020                        if (!checkin) {
15021                            pw.print("(apk) ");
15022                            pw.print(ent.apk);
15023                        } else {
15024                            pw.print(",apk,");
15025                            pw.print(ent.apk);
15026                        }
15027                    }
15028                    pw.println();
15029                }
15030            }
15031
15032            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15033                if (dumpState.onTitlePrinted())
15034                    pw.println();
15035                if (!checkin) {
15036                    pw.println("Features:");
15037                }
15038                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15039                while (it.hasNext()) {
15040                    String name = it.next();
15041                    if (!checkin) {
15042                        pw.print("  ");
15043                    } else {
15044                        pw.print("feat,");
15045                    }
15046                    pw.println(name);
15047                }
15048            }
15049
15050            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15051                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15052                        : "Activity Resolver Table:", "  ", packageName,
15053                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15054                    dumpState.setTitlePrinted(true);
15055                }
15056                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15057                        : "Receiver Resolver Table:", "  ", packageName,
15058                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15059                    dumpState.setTitlePrinted(true);
15060                }
15061                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15062                        : "Service Resolver Table:", "  ", packageName,
15063                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15064                    dumpState.setTitlePrinted(true);
15065                }
15066                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15067                        : "Provider Resolver Table:", "  ", packageName,
15068                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15069                    dumpState.setTitlePrinted(true);
15070                }
15071            }
15072
15073            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15074                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15075                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15076                    int user = mSettings.mPreferredActivities.keyAt(i);
15077                    if (pir.dump(pw,
15078                            dumpState.getTitlePrinted()
15079                                ? "\nPreferred Activities User " + user + ":"
15080                                : "Preferred Activities User " + user + ":", "  ",
15081                            packageName, true, false)) {
15082                        dumpState.setTitlePrinted(true);
15083                    }
15084                }
15085            }
15086
15087            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15088                pw.flush();
15089                FileOutputStream fout = new FileOutputStream(fd);
15090                BufferedOutputStream str = new BufferedOutputStream(fout);
15091                XmlSerializer serializer = new FastXmlSerializer();
15092                try {
15093                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15094                    serializer.startDocument(null, true);
15095                    serializer.setFeature(
15096                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15097                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15098                    serializer.endDocument();
15099                    serializer.flush();
15100                } catch (IllegalArgumentException e) {
15101                    pw.println("Failed writing: " + e);
15102                } catch (IllegalStateException e) {
15103                    pw.println("Failed writing: " + e);
15104                } catch (IOException e) {
15105                    pw.println("Failed writing: " + e);
15106                }
15107            }
15108
15109            if (!checkin
15110                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15111                    && packageName == null) {
15112                pw.println();
15113                int count = mSettings.mPackages.size();
15114                if (count == 0) {
15115                    pw.println("No applications!");
15116                    pw.println();
15117                } else {
15118                    final String prefix = "  ";
15119                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15120                    if (allPackageSettings.size() == 0) {
15121                        pw.println("No domain preferred apps!");
15122                        pw.println();
15123                    } else {
15124                        pw.println("App verification status:");
15125                        pw.println();
15126                        count = 0;
15127                        for (PackageSetting ps : allPackageSettings) {
15128                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15129                            if (ivi == null || ivi.getPackageName() == null) continue;
15130                            pw.println(prefix + "Package: " + ivi.getPackageName());
15131                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15132                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15133                            pw.println();
15134                            count++;
15135                        }
15136                        if (count == 0) {
15137                            pw.println(prefix + "No app verification established.");
15138                            pw.println();
15139                        }
15140                        for (int userId : sUserManager.getUserIds()) {
15141                            pw.println("App linkages for user " + userId + ":");
15142                            pw.println();
15143                            count = 0;
15144                            for (PackageSetting ps : allPackageSettings) {
15145                                final long status = ps.getDomainVerificationStatusForUser(userId);
15146                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15147                                    continue;
15148                                }
15149                                pw.println(prefix + "Package: " + ps.name);
15150                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15151                                String statusStr = IntentFilterVerificationInfo.
15152                                        getStatusStringFromValue(status);
15153                                pw.println(prefix + "Status:  " + statusStr);
15154                                pw.println();
15155                                count++;
15156                            }
15157                            if (count == 0) {
15158                                pw.println(prefix + "No configured app linkages.");
15159                                pw.println();
15160                            }
15161                        }
15162                    }
15163                }
15164            }
15165
15166            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15167                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15168                if (packageName == null && permissionNames == null) {
15169                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15170                        if (iperm == 0) {
15171                            if (dumpState.onTitlePrinted())
15172                                pw.println();
15173                            pw.println("AppOp Permissions:");
15174                        }
15175                        pw.print("  AppOp Permission ");
15176                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15177                        pw.println(":");
15178                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15179                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15180                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15181                        }
15182                    }
15183                }
15184            }
15185
15186            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15187                boolean printedSomething = false;
15188                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15189                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15190                        continue;
15191                    }
15192                    if (!printedSomething) {
15193                        if (dumpState.onTitlePrinted())
15194                            pw.println();
15195                        pw.println("Registered ContentProviders:");
15196                        printedSomething = true;
15197                    }
15198                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15199                    pw.print("    "); pw.println(p.toString());
15200                }
15201                printedSomething = false;
15202                for (Map.Entry<String, PackageParser.Provider> entry :
15203                        mProvidersByAuthority.entrySet()) {
15204                    PackageParser.Provider p = entry.getValue();
15205                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15206                        continue;
15207                    }
15208                    if (!printedSomething) {
15209                        if (dumpState.onTitlePrinted())
15210                            pw.println();
15211                        pw.println("ContentProvider Authorities:");
15212                        printedSomething = true;
15213                    }
15214                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15215                    pw.print("    "); pw.println(p.toString());
15216                    if (p.info != null && p.info.applicationInfo != null) {
15217                        final String appInfo = p.info.applicationInfo.toString();
15218                        pw.print("      applicationInfo="); pw.println(appInfo);
15219                    }
15220                }
15221            }
15222
15223            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15224                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15225            }
15226
15227            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15228                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15229            }
15230
15231            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15232                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15233            }
15234
15235            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15236                // XXX should handle packageName != null by dumping only install data that
15237                // the given package is involved with.
15238                if (dumpState.onTitlePrinted()) pw.println();
15239                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15240            }
15241
15242            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15243                if (dumpState.onTitlePrinted()) pw.println();
15244                mSettings.dumpReadMessagesLPr(pw, dumpState);
15245
15246                pw.println();
15247                pw.println("Package warning messages:");
15248                BufferedReader in = null;
15249                String line = null;
15250                try {
15251                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15252                    while ((line = in.readLine()) != null) {
15253                        if (line.contains("ignored: updated version")) continue;
15254                        pw.println(line);
15255                    }
15256                } catch (IOException ignored) {
15257                } finally {
15258                    IoUtils.closeQuietly(in);
15259                }
15260            }
15261
15262            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15263                BufferedReader in = null;
15264                String line = null;
15265                try {
15266                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15267                    while ((line = in.readLine()) != null) {
15268                        if (line.contains("ignored: updated version")) continue;
15269                        pw.print("msg,");
15270                        pw.println(line);
15271                    }
15272                } catch (IOException ignored) {
15273                } finally {
15274                    IoUtils.closeQuietly(in);
15275                }
15276            }
15277        }
15278    }
15279
15280    private String dumpDomainString(String packageName) {
15281        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15282        List<IntentFilter> filters = getAllIntentFilters(packageName);
15283
15284        ArraySet<String> result = new ArraySet<>();
15285        if (iviList.size() > 0) {
15286            for (IntentFilterVerificationInfo ivi : iviList) {
15287                for (String host : ivi.getDomains()) {
15288                    result.add(host);
15289                }
15290            }
15291        }
15292        if (filters != null && filters.size() > 0) {
15293            for (IntentFilter filter : filters) {
15294                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15295                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15296                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15297                    result.addAll(filter.getHostsList());
15298                }
15299            }
15300        }
15301
15302        StringBuilder sb = new StringBuilder(result.size() * 16);
15303        for (String domain : result) {
15304            if (sb.length() > 0) sb.append(" ");
15305            sb.append(domain);
15306        }
15307        return sb.toString();
15308    }
15309
15310    // ------- apps on sdcard specific code -------
15311    static final boolean DEBUG_SD_INSTALL = false;
15312
15313    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15314
15315    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15316
15317    private boolean mMediaMounted = false;
15318
15319    static String getEncryptKey() {
15320        try {
15321            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15322                    SD_ENCRYPTION_KEYSTORE_NAME);
15323            if (sdEncKey == null) {
15324                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15325                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15326                if (sdEncKey == null) {
15327                    Slog.e(TAG, "Failed to create encryption keys");
15328                    return null;
15329                }
15330            }
15331            return sdEncKey;
15332        } catch (NoSuchAlgorithmException nsae) {
15333            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15334            return null;
15335        } catch (IOException ioe) {
15336            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15337            return null;
15338        }
15339    }
15340
15341    /*
15342     * Update media status on PackageManager.
15343     */
15344    @Override
15345    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15346        int callingUid = Binder.getCallingUid();
15347        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15348            throw new SecurityException("Media status can only be updated by the system");
15349        }
15350        // reader; this apparently protects mMediaMounted, but should probably
15351        // be a different lock in that case.
15352        synchronized (mPackages) {
15353            Log.i(TAG, "Updating external media status from "
15354                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15355                    + (mediaStatus ? "mounted" : "unmounted"));
15356            if (DEBUG_SD_INSTALL)
15357                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15358                        + ", mMediaMounted=" + mMediaMounted);
15359            if (mediaStatus == mMediaMounted) {
15360                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15361                        : 0, -1);
15362                mHandler.sendMessage(msg);
15363                return;
15364            }
15365            mMediaMounted = mediaStatus;
15366        }
15367        // Queue up an async operation since the package installation may take a
15368        // little while.
15369        mHandler.post(new Runnable() {
15370            public void run() {
15371                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15372            }
15373        });
15374    }
15375
15376    /**
15377     * Called by MountService when the initial ASECs to scan are available.
15378     * Should block until all the ASEC containers are finished being scanned.
15379     */
15380    public void scanAvailableAsecs() {
15381        updateExternalMediaStatusInner(true, false, false);
15382        if (mShouldRestoreconData) {
15383            SELinuxMMAC.setRestoreconDone();
15384            mShouldRestoreconData = false;
15385        }
15386    }
15387
15388    /*
15389     * Collect information of applications on external media, map them against
15390     * existing containers and update information based on current mount status.
15391     * Please note that we always have to report status if reportStatus has been
15392     * set to true especially when unloading packages.
15393     */
15394    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15395            boolean externalStorage) {
15396        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15397        int[] uidArr = EmptyArray.INT;
15398
15399        final String[] list = PackageHelper.getSecureContainerList();
15400        if (ArrayUtils.isEmpty(list)) {
15401            Log.i(TAG, "No secure containers found");
15402        } else {
15403            // Process list of secure containers and categorize them
15404            // as active or stale based on their package internal state.
15405
15406            // reader
15407            synchronized (mPackages) {
15408                for (String cid : list) {
15409                    // Leave stages untouched for now; installer service owns them
15410                    if (PackageInstallerService.isStageName(cid)) continue;
15411
15412                    if (DEBUG_SD_INSTALL)
15413                        Log.i(TAG, "Processing container " + cid);
15414                    String pkgName = getAsecPackageName(cid);
15415                    if (pkgName == null) {
15416                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15417                        continue;
15418                    }
15419                    if (DEBUG_SD_INSTALL)
15420                        Log.i(TAG, "Looking for pkg : " + pkgName);
15421
15422                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15423                    if (ps == null) {
15424                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15425                        continue;
15426                    }
15427
15428                    /*
15429                     * Skip packages that are not external if we're unmounting
15430                     * external storage.
15431                     */
15432                    if (externalStorage && !isMounted && !isExternal(ps)) {
15433                        continue;
15434                    }
15435
15436                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15437                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15438                    // The package status is changed only if the code path
15439                    // matches between settings and the container id.
15440                    if (ps.codePathString != null
15441                            && ps.codePathString.startsWith(args.getCodePath())) {
15442                        if (DEBUG_SD_INSTALL) {
15443                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15444                                    + " at code path: " + ps.codePathString);
15445                        }
15446
15447                        // We do have a valid package installed on sdcard
15448                        processCids.put(args, ps.codePathString);
15449                        final int uid = ps.appId;
15450                        if (uid != -1) {
15451                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15452                        }
15453                    } else {
15454                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15455                                + ps.codePathString);
15456                    }
15457                }
15458            }
15459
15460            Arrays.sort(uidArr);
15461        }
15462
15463        // Process packages with valid entries.
15464        if (isMounted) {
15465            if (DEBUG_SD_INSTALL)
15466                Log.i(TAG, "Loading packages");
15467            loadMediaPackages(processCids, uidArr);
15468            startCleaningPackages();
15469            mInstallerService.onSecureContainersAvailable();
15470        } else {
15471            if (DEBUG_SD_INSTALL)
15472                Log.i(TAG, "Unloading packages");
15473            unloadMediaPackages(processCids, uidArr, reportStatus);
15474        }
15475    }
15476
15477    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15478            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15479        final int size = infos.size();
15480        final String[] packageNames = new String[size];
15481        final int[] packageUids = new int[size];
15482        for (int i = 0; i < size; i++) {
15483            final ApplicationInfo info = infos.get(i);
15484            packageNames[i] = info.packageName;
15485            packageUids[i] = info.uid;
15486        }
15487        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15488                finishedReceiver);
15489    }
15490
15491    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15492            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15493        sendResourcesChangedBroadcast(mediaStatus, replacing,
15494                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15495    }
15496
15497    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15498            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15499        int size = pkgList.length;
15500        if (size > 0) {
15501            // Send broadcasts here
15502            Bundle extras = new Bundle();
15503            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15504            if (uidArr != null) {
15505                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15506            }
15507            if (replacing) {
15508                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15509            }
15510            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15511                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15512            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15513        }
15514    }
15515
15516   /*
15517     * Look at potentially valid container ids from processCids If package
15518     * information doesn't match the one on record or package scanning fails,
15519     * the cid is added to list of removeCids. We currently don't delete stale
15520     * containers.
15521     */
15522    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15523        ArrayList<String> pkgList = new ArrayList<String>();
15524        Set<AsecInstallArgs> keys = processCids.keySet();
15525
15526        for (AsecInstallArgs args : keys) {
15527            String codePath = processCids.get(args);
15528            if (DEBUG_SD_INSTALL)
15529                Log.i(TAG, "Loading container : " + args.cid);
15530            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15531            try {
15532                // Make sure there are no container errors first.
15533                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15534                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15535                            + " when installing from sdcard");
15536                    continue;
15537                }
15538                // Check code path here.
15539                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15540                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15541                            + " does not match one in settings " + codePath);
15542                    continue;
15543                }
15544                // Parse package
15545                int parseFlags = mDefParseFlags;
15546                if (args.isExternalAsec()) {
15547                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15548                }
15549                if (args.isFwdLocked()) {
15550                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15551                }
15552
15553                synchronized (mInstallLock) {
15554                    PackageParser.Package pkg = null;
15555                    try {
15556                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15557                    } catch (PackageManagerException e) {
15558                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15559                    }
15560                    // Scan the package
15561                    if (pkg != null) {
15562                        /*
15563                         * TODO why is the lock being held? doPostInstall is
15564                         * called in other places without the lock. This needs
15565                         * to be straightened out.
15566                         */
15567                        // writer
15568                        synchronized (mPackages) {
15569                            retCode = PackageManager.INSTALL_SUCCEEDED;
15570                            pkgList.add(pkg.packageName);
15571                            // Post process args
15572                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15573                                    pkg.applicationInfo.uid);
15574                        }
15575                    } else {
15576                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15577                    }
15578                }
15579
15580            } finally {
15581                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15582                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15583                }
15584            }
15585        }
15586        // writer
15587        synchronized (mPackages) {
15588            // If the platform SDK has changed since the last time we booted,
15589            // we need to re-grant app permission to catch any new ones that
15590            // appear. This is really a hack, and means that apps can in some
15591            // cases get permissions that the user didn't initially explicitly
15592            // allow... it would be nice to have some better way to handle
15593            // this situation.
15594            final VersionInfo ver = mSettings.getExternalVersion();
15595
15596            int updateFlags = UPDATE_PERMISSIONS_ALL;
15597            if (ver.sdkVersion != mSdkVersion) {
15598                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15599                        + mSdkVersion + "; regranting permissions for external");
15600                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15601            }
15602            updatePermissionsLPw(null, null, updateFlags);
15603
15604            // Yay, everything is now upgraded
15605            ver.forceCurrent();
15606
15607            // can downgrade to reader
15608            // Persist settings
15609            mSettings.writeLPr();
15610        }
15611        // Send a broadcast to let everyone know we are done processing
15612        if (pkgList.size() > 0) {
15613            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15614        }
15615    }
15616
15617   /*
15618     * Utility method to unload a list of specified containers
15619     */
15620    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15621        // Just unmount all valid containers.
15622        for (AsecInstallArgs arg : cidArgs) {
15623            synchronized (mInstallLock) {
15624                arg.doPostDeleteLI(false);
15625           }
15626       }
15627   }
15628
15629    /*
15630     * Unload packages mounted on external media. This involves deleting package
15631     * data from internal structures, sending broadcasts about diabled packages,
15632     * gc'ing to free up references, unmounting all secure containers
15633     * corresponding to packages on external media, and posting a
15634     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15635     * that we always have to post this message if status has been requested no
15636     * matter what.
15637     */
15638    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15639            final boolean reportStatus) {
15640        if (DEBUG_SD_INSTALL)
15641            Log.i(TAG, "unloading media packages");
15642        ArrayList<String> pkgList = new ArrayList<String>();
15643        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15644        final Set<AsecInstallArgs> keys = processCids.keySet();
15645        for (AsecInstallArgs args : keys) {
15646            String pkgName = args.getPackageName();
15647            if (DEBUG_SD_INSTALL)
15648                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15649            // Delete package internally
15650            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15651            synchronized (mInstallLock) {
15652                boolean res = deletePackageLI(pkgName, null, false, null, null,
15653                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15654                if (res) {
15655                    pkgList.add(pkgName);
15656                } else {
15657                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15658                    failedList.add(args);
15659                }
15660            }
15661        }
15662
15663        // reader
15664        synchronized (mPackages) {
15665            // We didn't update the settings after removing each package;
15666            // write them now for all packages.
15667            mSettings.writeLPr();
15668        }
15669
15670        // We have to absolutely send UPDATED_MEDIA_STATUS only
15671        // after confirming that all the receivers processed the ordered
15672        // broadcast when packages get disabled, force a gc to clean things up.
15673        // and unload all the containers.
15674        if (pkgList.size() > 0) {
15675            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15676                    new IIntentReceiver.Stub() {
15677                public void performReceive(Intent intent, int resultCode, String data,
15678                        Bundle extras, boolean ordered, boolean sticky,
15679                        int sendingUser) throws RemoteException {
15680                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15681                            reportStatus ? 1 : 0, 1, keys);
15682                    mHandler.sendMessage(msg);
15683                }
15684            });
15685        } else {
15686            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15687                    keys);
15688            mHandler.sendMessage(msg);
15689        }
15690    }
15691
15692    private void loadPrivatePackages(final VolumeInfo vol) {
15693        mHandler.post(new Runnable() {
15694            @Override
15695            public void run() {
15696                loadPrivatePackagesInner(vol);
15697            }
15698        });
15699    }
15700
15701    private void loadPrivatePackagesInner(VolumeInfo vol) {
15702        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15703        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15704
15705        final VersionInfo ver;
15706        final List<PackageSetting> packages;
15707        synchronized (mPackages) {
15708            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15709            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15710        }
15711
15712        for (PackageSetting ps : packages) {
15713            synchronized (mInstallLock) {
15714                final PackageParser.Package pkg;
15715                try {
15716                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15717                    loaded.add(pkg.applicationInfo);
15718                } catch (PackageManagerException e) {
15719                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15720                }
15721
15722                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15723                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15724                }
15725            }
15726        }
15727
15728        synchronized (mPackages) {
15729            int updateFlags = UPDATE_PERMISSIONS_ALL;
15730            if (ver.sdkVersion != mSdkVersion) {
15731                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15732                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15733                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15734            }
15735            updatePermissionsLPw(null, null, updateFlags);
15736
15737            // Yay, everything is now upgraded
15738            ver.forceCurrent();
15739
15740            mSettings.writeLPr();
15741        }
15742
15743        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15744        sendResourcesChangedBroadcast(true, false, loaded, null);
15745    }
15746
15747    private void unloadPrivatePackages(final VolumeInfo vol) {
15748        mHandler.post(new Runnable() {
15749            @Override
15750            public void run() {
15751                unloadPrivatePackagesInner(vol);
15752            }
15753        });
15754    }
15755
15756    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15757        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15758        synchronized (mInstallLock) {
15759        synchronized (mPackages) {
15760            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15761            for (PackageSetting ps : packages) {
15762                if (ps.pkg == null) continue;
15763
15764                final ApplicationInfo info = ps.pkg.applicationInfo;
15765                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15766                if (deletePackageLI(ps.name, null, false, null, null,
15767                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15768                    unloaded.add(info);
15769                } else {
15770                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15771                }
15772            }
15773
15774            mSettings.writeLPr();
15775        }
15776        }
15777
15778        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15779        sendResourcesChangedBroadcast(false, false, unloaded, null);
15780    }
15781
15782    /**
15783     * Examine all users present on given mounted volume, and destroy data
15784     * belonging to users that are no longer valid, or whose user ID has been
15785     * recycled.
15786     */
15787    private void reconcileUsers(String volumeUuid) {
15788        final File[] files = FileUtils
15789                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15790        for (File file : files) {
15791            if (!file.isDirectory()) continue;
15792
15793            final int userId;
15794            final UserInfo info;
15795            try {
15796                userId = Integer.parseInt(file.getName());
15797                info = sUserManager.getUserInfo(userId);
15798            } catch (NumberFormatException e) {
15799                Slog.w(TAG, "Invalid user directory " + file);
15800                continue;
15801            }
15802
15803            boolean destroyUser = false;
15804            if (info == null) {
15805                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15806                        + " because no matching user was found");
15807                destroyUser = true;
15808            } else {
15809                try {
15810                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15811                } catch (IOException e) {
15812                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15813                            + " because we failed to enforce serial number: " + e);
15814                    destroyUser = true;
15815                }
15816            }
15817
15818            if (destroyUser) {
15819                synchronized (mInstallLock) {
15820                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15821                }
15822            }
15823        }
15824
15825        final UserManager um = mContext.getSystemService(UserManager.class);
15826        for (UserInfo user : um.getUsers()) {
15827            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15828            if (userDir.exists()) continue;
15829
15830            try {
15831                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15832                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15833            } catch (IOException e) {
15834                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15835            }
15836        }
15837    }
15838
15839    /**
15840     * Examine all apps present on given mounted volume, and destroy apps that
15841     * aren't expected, either due to uninstallation or reinstallation on
15842     * another volume.
15843     */
15844    private void reconcileApps(String volumeUuid) {
15845        final File[] files = FileUtils
15846                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15847        for (File file : files) {
15848            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15849                    && !PackageInstallerService.isStageName(file.getName());
15850            if (!isPackage) {
15851                // Ignore entries which are not packages
15852                continue;
15853            }
15854
15855            boolean destroyApp = false;
15856            String packageName = null;
15857            try {
15858                final PackageLite pkg = PackageParser.parsePackageLite(file,
15859                        PackageParser.PARSE_MUST_BE_APK);
15860                packageName = pkg.packageName;
15861
15862                synchronized (mPackages) {
15863                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15864                    if (ps == null) {
15865                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15866                                + volumeUuid + " because we found no install record");
15867                        destroyApp = true;
15868                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15869                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15870                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15871                        destroyApp = true;
15872                    }
15873                }
15874
15875            } catch (PackageParserException e) {
15876                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15877                destroyApp = true;
15878            }
15879
15880            if (destroyApp) {
15881                synchronized (mInstallLock) {
15882                    if (packageName != null) {
15883                        removeDataDirsLI(volumeUuid, packageName);
15884                    }
15885                    if (file.isDirectory()) {
15886                        mInstaller.rmPackageDir(file.getAbsolutePath());
15887                    } else {
15888                        file.delete();
15889                    }
15890                }
15891            }
15892        }
15893    }
15894
15895    private void unfreezePackage(String packageName) {
15896        synchronized (mPackages) {
15897            final PackageSetting ps = mSettings.mPackages.get(packageName);
15898            if (ps != null) {
15899                ps.frozen = false;
15900            }
15901        }
15902    }
15903
15904    @Override
15905    public int movePackage(final String packageName, final String volumeUuid) {
15906        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15907
15908        final int moveId = mNextMoveId.getAndIncrement();
15909        try {
15910            movePackageInternal(packageName, volumeUuid, moveId);
15911        } catch (PackageManagerException e) {
15912            Slog.w(TAG, "Failed to move " + packageName, e);
15913            mMoveCallbacks.notifyStatusChanged(moveId,
15914                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15915        }
15916        return moveId;
15917    }
15918
15919    private void movePackageInternal(final String packageName, final String volumeUuid,
15920            final int moveId) throws PackageManagerException {
15921        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15922        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15923        final PackageManager pm = mContext.getPackageManager();
15924
15925        final boolean currentAsec;
15926        final String currentVolumeUuid;
15927        final File codeFile;
15928        final String installerPackageName;
15929        final String packageAbiOverride;
15930        final int appId;
15931        final String seinfo;
15932        final String label;
15933
15934        // reader
15935        synchronized (mPackages) {
15936            final PackageParser.Package pkg = mPackages.get(packageName);
15937            final PackageSetting ps = mSettings.mPackages.get(packageName);
15938            if (pkg == null || ps == null) {
15939                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15940            }
15941
15942            if (pkg.applicationInfo.isSystemApp()) {
15943                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15944                        "Cannot move system application");
15945            }
15946
15947            if (pkg.applicationInfo.isExternalAsec()) {
15948                currentAsec = true;
15949                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15950            } else if (pkg.applicationInfo.isForwardLocked()) {
15951                currentAsec = true;
15952                currentVolumeUuid = "forward_locked";
15953            } else {
15954                currentAsec = false;
15955                currentVolumeUuid = ps.volumeUuid;
15956
15957                final File probe = new File(pkg.codePath);
15958                final File probeOat = new File(probe, "oat");
15959                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15960                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15961                            "Move only supported for modern cluster style installs");
15962                }
15963            }
15964
15965            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15966                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15967                        "Package already moved to " + volumeUuid);
15968            }
15969
15970            if (ps.frozen) {
15971                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15972                        "Failed to move already frozen package");
15973            }
15974            ps.frozen = true;
15975
15976            codeFile = new File(pkg.codePath);
15977            installerPackageName = ps.installerPackageName;
15978            packageAbiOverride = ps.cpuAbiOverrideString;
15979            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15980            seinfo = pkg.applicationInfo.seinfo;
15981            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15982        }
15983
15984        // Now that we're guarded by frozen state, kill app during move
15985        final long token = Binder.clearCallingIdentity();
15986        try {
15987            killApplication(packageName, appId, "move pkg");
15988        } finally {
15989            Binder.restoreCallingIdentity(token);
15990        }
15991
15992        final Bundle extras = new Bundle();
15993        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15994        extras.putString(Intent.EXTRA_TITLE, label);
15995        mMoveCallbacks.notifyCreated(moveId, extras);
15996
15997        int installFlags;
15998        final boolean moveCompleteApp;
15999        final File measurePath;
16000
16001        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16002            installFlags = INSTALL_INTERNAL;
16003            moveCompleteApp = !currentAsec;
16004            measurePath = Environment.getDataAppDirectory(volumeUuid);
16005        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16006            installFlags = INSTALL_EXTERNAL;
16007            moveCompleteApp = false;
16008            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16009        } else {
16010            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16011            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16012                    || !volume.isMountedWritable()) {
16013                unfreezePackage(packageName);
16014                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16015                        "Move location not mounted private volume");
16016            }
16017
16018            Preconditions.checkState(!currentAsec);
16019
16020            installFlags = INSTALL_INTERNAL;
16021            moveCompleteApp = true;
16022            measurePath = Environment.getDataAppDirectory(volumeUuid);
16023        }
16024
16025        final PackageStats stats = new PackageStats(null, -1);
16026        synchronized (mInstaller) {
16027            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16028                unfreezePackage(packageName);
16029                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16030                        "Failed to measure package size");
16031            }
16032        }
16033
16034        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16035                + stats.dataSize);
16036
16037        final long startFreeBytes = measurePath.getFreeSpace();
16038        final long sizeBytes;
16039        if (moveCompleteApp) {
16040            sizeBytes = stats.codeSize + stats.dataSize;
16041        } else {
16042            sizeBytes = stats.codeSize;
16043        }
16044
16045        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16046            unfreezePackage(packageName);
16047            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16048                    "Not enough free space to move");
16049        }
16050
16051        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16052
16053        final CountDownLatch installedLatch = new CountDownLatch(1);
16054        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16055            @Override
16056            public void onUserActionRequired(Intent intent) throws RemoteException {
16057                throw new IllegalStateException();
16058            }
16059
16060            @Override
16061            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16062                    Bundle extras) throws RemoteException {
16063                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16064                        + PackageManager.installStatusToString(returnCode, msg));
16065
16066                installedLatch.countDown();
16067
16068                // Regardless of success or failure of the move operation,
16069                // always unfreeze the package
16070                unfreezePackage(packageName);
16071
16072                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16073                switch (status) {
16074                    case PackageInstaller.STATUS_SUCCESS:
16075                        mMoveCallbacks.notifyStatusChanged(moveId,
16076                                PackageManager.MOVE_SUCCEEDED);
16077                        break;
16078                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16079                        mMoveCallbacks.notifyStatusChanged(moveId,
16080                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16081                        break;
16082                    default:
16083                        mMoveCallbacks.notifyStatusChanged(moveId,
16084                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16085                        break;
16086                }
16087            }
16088        };
16089
16090        final MoveInfo move;
16091        if (moveCompleteApp) {
16092            // Kick off a thread to report progress estimates
16093            new Thread() {
16094                @Override
16095                public void run() {
16096                    while (true) {
16097                        try {
16098                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16099                                break;
16100                            }
16101                        } catch (InterruptedException ignored) {
16102                        }
16103
16104                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16105                        final int progress = 10 + (int) MathUtils.constrain(
16106                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16107                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16108                    }
16109                }
16110            }.start();
16111
16112            final String dataAppName = codeFile.getName();
16113            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16114                    dataAppName, appId, seinfo);
16115        } else {
16116            move = null;
16117        }
16118
16119        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16120
16121        final Message msg = mHandler.obtainMessage(INIT_COPY);
16122        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16123        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16124                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16125        mHandler.sendMessage(msg);
16126    }
16127
16128    @Override
16129    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16130        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16131
16132        final int realMoveId = mNextMoveId.getAndIncrement();
16133        final Bundle extras = new Bundle();
16134        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16135        mMoveCallbacks.notifyCreated(realMoveId, extras);
16136
16137        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16138            @Override
16139            public void onCreated(int moveId, Bundle extras) {
16140                // Ignored
16141            }
16142
16143            @Override
16144            public void onStatusChanged(int moveId, int status, long estMillis) {
16145                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16146            }
16147        };
16148
16149        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16150        storage.setPrimaryStorageUuid(volumeUuid, callback);
16151        return realMoveId;
16152    }
16153
16154    @Override
16155    public int getMoveStatus(int moveId) {
16156        mContext.enforceCallingOrSelfPermission(
16157                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16158        return mMoveCallbacks.mLastStatus.get(moveId);
16159    }
16160
16161    @Override
16162    public void registerMoveCallback(IPackageMoveObserver callback) {
16163        mContext.enforceCallingOrSelfPermission(
16164                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16165        mMoveCallbacks.register(callback);
16166    }
16167
16168    @Override
16169    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16170        mContext.enforceCallingOrSelfPermission(
16171                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16172        mMoveCallbacks.unregister(callback);
16173    }
16174
16175    @Override
16176    public boolean setInstallLocation(int loc) {
16177        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16178                null);
16179        if (getInstallLocation() == loc) {
16180            return true;
16181        }
16182        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16183                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16184            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16185                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16186            return true;
16187        }
16188        return false;
16189   }
16190
16191    @Override
16192    public int getInstallLocation() {
16193        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16194                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16195                PackageHelper.APP_INSTALL_AUTO);
16196    }
16197
16198    /** Called by UserManagerService */
16199    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16200        mDirtyUsers.remove(userHandle);
16201        mSettings.removeUserLPw(userHandle);
16202        mPendingBroadcasts.remove(userHandle);
16203        if (mInstaller != null) {
16204            // Technically, we shouldn't be doing this with the package lock
16205            // held.  However, this is very rare, and there is already so much
16206            // other disk I/O going on, that we'll let it slide for now.
16207            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16208            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16209                final String volumeUuid = vol.getFsUuid();
16210                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16211                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16212            }
16213        }
16214        mUserNeedsBadging.delete(userHandle);
16215        removeUnusedPackagesLILPw(userManager, userHandle);
16216    }
16217
16218    /**
16219     * We're removing userHandle and would like to remove any downloaded packages
16220     * that are no longer in use by any other user.
16221     * @param userHandle the user being removed
16222     */
16223    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16224        final boolean DEBUG_CLEAN_APKS = false;
16225        int [] users = userManager.getUserIdsLPr();
16226        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16227        while (psit.hasNext()) {
16228            PackageSetting ps = psit.next();
16229            if (ps.pkg == null) {
16230                continue;
16231            }
16232            final String packageName = ps.pkg.packageName;
16233            // Skip over if system app
16234            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16235                continue;
16236            }
16237            if (DEBUG_CLEAN_APKS) {
16238                Slog.i(TAG, "Checking package " + packageName);
16239            }
16240            boolean keep = false;
16241            for (int i = 0; i < users.length; i++) {
16242                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16243                    keep = true;
16244                    if (DEBUG_CLEAN_APKS) {
16245                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16246                                + users[i]);
16247                    }
16248                    break;
16249                }
16250            }
16251            if (!keep) {
16252                if (DEBUG_CLEAN_APKS) {
16253                    Slog.i(TAG, "  Removing package " + packageName);
16254                }
16255                mHandler.post(new Runnable() {
16256                    public void run() {
16257                        deletePackageX(packageName, userHandle, 0);
16258                    } //end run
16259                });
16260            }
16261        }
16262    }
16263
16264    /** Called by UserManagerService */
16265    void createNewUserLILPw(int userHandle) {
16266        if (mInstaller != null) {
16267            mInstaller.createUserConfig(userHandle);
16268            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16269            applyFactoryDefaultBrowserLPw(userHandle);
16270            primeDomainVerificationsLPw(userHandle);
16271        }
16272    }
16273
16274    void newUserCreated(final int userHandle) {
16275        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16276    }
16277
16278    @Override
16279    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16280        mContext.enforceCallingOrSelfPermission(
16281                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16282                "Only package verification agents can read the verifier device identity");
16283
16284        synchronized (mPackages) {
16285            return mSettings.getVerifierDeviceIdentityLPw();
16286        }
16287    }
16288
16289    @Override
16290    public void setPermissionEnforced(String permission, boolean enforced) {
16291        // TODO: Now that we no longer change GID for storage, this should to away.
16292        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16293                "setPermissionEnforced");
16294        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16295            synchronized (mPackages) {
16296                if (mSettings.mReadExternalStorageEnforced == null
16297                        || mSettings.mReadExternalStorageEnforced != enforced) {
16298                    mSettings.mReadExternalStorageEnforced = enforced;
16299                    mSettings.writeLPr();
16300                }
16301            }
16302            // kill any non-foreground processes so we restart them and
16303            // grant/revoke the GID.
16304            final IActivityManager am = ActivityManagerNative.getDefault();
16305            if (am != null) {
16306                final long token = Binder.clearCallingIdentity();
16307                try {
16308                    am.killProcessesBelowForeground("setPermissionEnforcement");
16309                } catch (RemoteException e) {
16310                } finally {
16311                    Binder.restoreCallingIdentity(token);
16312                }
16313            }
16314        } else {
16315            throw new IllegalArgumentException("No selective enforcement for " + permission);
16316        }
16317    }
16318
16319    @Override
16320    @Deprecated
16321    public boolean isPermissionEnforced(String permission) {
16322        return true;
16323    }
16324
16325    @Override
16326    public boolean isStorageLow() {
16327        final long token = Binder.clearCallingIdentity();
16328        try {
16329            final DeviceStorageMonitorInternal
16330                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16331            if (dsm != null) {
16332                return dsm.isMemoryLow();
16333            } else {
16334                return false;
16335            }
16336        } finally {
16337            Binder.restoreCallingIdentity(token);
16338        }
16339    }
16340
16341    @Override
16342    public IPackageInstaller getPackageInstaller() {
16343        return mInstallerService;
16344    }
16345
16346    private boolean userNeedsBadging(int userId) {
16347        int index = mUserNeedsBadging.indexOfKey(userId);
16348        if (index < 0) {
16349            final UserInfo userInfo;
16350            final long token = Binder.clearCallingIdentity();
16351            try {
16352                userInfo = sUserManager.getUserInfo(userId);
16353            } finally {
16354                Binder.restoreCallingIdentity(token);
16355            }
16356            final boolean b;
16357            if (userInfo != null && userInfo.isManagedProfile()) {
16358                b = true;
16359            } else {
16360                b = false;
16361            }
16362            mUserNeedsBadging.put(userId, b);
16363            return b;
16364        }
16365        return mUserNeedsBadging.valueAt(index);
16366    }
16367
16368    @Override
16369    public KeySet getKeySetByAlias(String packageName, String alias) {
16370        if (packageName == null || alias == null) {
16371            return null;
16372        }
16373        synchronized(mPackages) {
16374            final PackageParser.Package pkg = mPackages.get(packageName);
16375            if (pkg == null) {
16376                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16377                throw new IllegalArgumentException("Unknown package: " + packageName);
16378            }
16379            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16380            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16381        }
16382    }
16383
16384    @Override
16385    public KeySet getSigningKeySet(String packageName) {
16386        if (packageName == null) {
16387            return null;
16388        }
16389        synchronized(mPackages) {
16390            final PackageParser.Package pkg = mPackages.get(packageName);
16391            if (pkg == null) {
16392                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16393                throw new IllegalArgumentException("Unknown package: " + packageName);
16394            }
16395            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16396                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16397                throw new SecurityException("May not access signing KeySet of other apps.");
16398            }
16399            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16400            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16401        }
16402    }
16403
16404    @Override
16405    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16406        if (packageName == null || ks == null) {
16407            return false;
16408        }
16409        synchronized(mPackages) {
16410            final PackageParser.Package pkg = mPackages.get(packageName);
16411            if (pkg == null) {
16412                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16413                throw new IllegalArgumentException("Unknown package: " + packageName);
16414            }
16415            IBinder ksh = ks.getToken();
16416            if (ksh instanceof KeySetHandle) {
16417                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16418                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16419            }
16420            return false;
16421        }
16422    }
16423
16424    @Override
16425    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16426        if (packageName == null || ks == null) {
16427            return false;
16428        }
16429        synchronized(mPackages) {
16430            final PackageParser.Package pkg = mPackages.get(packageName);
16431            if (pkg == null) {
16432                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16433                throw new IllegalArgumentException("Unknown package: " + packageName);
16434            }
16435            IBinder ksh = ks.getToken();
16436            if (ksh instanceof KeySetHandle) {
16437                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16438                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16439            }
16440            return false;
16441        }
16442    }
16443
16444    public void getUsageStatsIfNoPackageUsageInfo() {
16445        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16446            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16447            if (usm == null) {
16448                throw new IllegalStateException("UsageStatsManager must be initialized");
16449            }
16450            long now = System.currentTimeMillis();
16451            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16452            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16453                String packageName = entry.getKey();
16454                PackageParser.Package pkg = mPackages.get(packageName);
16455                if (pkg == null) {
16456                    continue;
16457                }
16458                UsageStats usage = entry.getValue();
16459                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16460                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16461            }
16462        }
16463    }
16464
16465    /**
16466     * Check and throw if the given before/after packages would be considered a
16467     * downgrade.
16468     */
16469    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16470            throws PackageManagerException {
16471        if (after.versionCode < before.mVersionCode) {
16472            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16473                    "Update version code " + after.versionCode + " is older than current "
16474                    + before.mVersionCode);
16475        } else if (after.versionCode == before.mVersionCode) {
16476            if (after.baseRevisionCode < before.baseRevisionCode) {
16477                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16478                        "Update base revision code " + after.baseRevisionCode
16479                        + " is older than current " + before.baseRevisionCode);
16480            }
16481
16482            if (!ArrayUtils.isEmpty(after.splitNames)) {
16483                for (int i = 0; i < after.splitNames.length; i++) {
16484                    final String splitName = after.splitNames[i];
16485                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16486                    if (j != -1) {
16487                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16488                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16489                                    "Update split " + splitName + " revision code "
16490                                    + after.splitRevisionCodes[i] + " is older than current "
16491                                    + before.splitRevisionCodes[j]);
16492                        }
16493                    }
16494                }
16495            }
16496        }
16497    }
16498
16499    private static class MoveCallbacks extends Handler {
16500        private static final int MSG_CREATED = 1;
16501        private static final int MSG_STATUS_CHANGED = 2;
16502
16503        private final RemoteCallbackList<IPackageMoveObserver>
16504                mCallbacks = new RemoteCallbackList<>();
16505
16506        private final SparseIntArray mLastStatus = new SparseIntArray();
16507
16508        public MoveCallbacks(Looper looper) {
16509            super(looper);
16510        }
16511
16512        public void register(IPackageMoveObserver callback) {
16513            mCallbacks.register(callback);
16514        }
16515
16516        public void unregister(IPackageMoveObserver callback) {
16517            mCallbacks.unregister(callback);
16518        }
16519
16520        @Override
16521        public void handleMessage(Message msg) {
16522            final SomeArgs args = (SomeArgs) msg.obj;
16523            final int n = mCallbacks.beginBroadcast();
16524            for (int i = 0; i < n; i++) {
16525                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16526                try {
16527                    invokeCallback(callback, msg.what, args);
16528                } catch (RemoteException ignored) {
16529                }
16530            }
16531            mCallbacks.finishBroadcast();
16532            args.recycle();
16533        }
16534
16535        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16536                throws RemoteException {
16537            switch (what) {
16538                case MSG_CREATED: {
16539                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16540                    break;
16541                }
16542                case MSG_STATUS_CHANGED: {
16543                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16544                    break;
16545                }
16546            }
16547        }
16548
16549        private void notifyCreated(int moveId, Bundle extras) {
16550            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16551
16552            final SomeArgs args = SomeArgs.obtain();
16553            args.argi1 = moveId;
16554            args.arg2 = extras;
16555            obtainMessage(MSG_CREATED, args).sendToTarget();
16556        }
16557
16558        private void notifyStatusChanged(int moveId, int status) {
16559            notifyStatusChanged(moveId, status, -1);
16560        }
16561
16562        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16563            Slog.v(TAG, "Move " + moveId + " status " + status);
16564
16565            final SomeArgs args = SomeArgs.obtain();
16566            args.argi1 = moveId;
16567            args.argi2 = status;
16568            args.arg3 = estMillis;
16569            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16570
16571            synchronized (mLastStatus) {
16572                mLastStatus.put(moveId, status);
16573            }
16574        }
16575    }
16576
16577    private final class OnPermissionChangeListeners extends Handler {
16578        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16579
16580        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16581                new RemoteCallbackList<>();
16582
16583        public OnPermissionChangeListeners(Looper looper) {
16584            super(looper);
16585        }
16586
16587        @Override
16588        public void handleMessage(Message msg) {
16589            switch (msg.what) {
16590                case MSG_ON_PERMISSIONS_CHANGED: {
16591                    final int uid = msg.arg1;
16592                    handleOnPermissionsChanged(uid);
16593                } break;
16594            }
16595        }
16596
16597        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16598            mPermissionListeners.register(listener);
16599
16600        }
16601
16602        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16603            mPermissionListeners.unregister(listener);
16604        }
16605
16606        public void onPermissionsChanged(int uid) {
16607            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16608                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16609            }
16610        }
16611
16612        private void handleOnPermissionsChanged(int uid) {
16613            final int count = mPermissionListeners.beginBroadcast();
16614            try {
16615                for (int i = 0; i < count; i++) {
16616                    IOnPermissionsChangeListener callback = mPermissionListeners
16617                            .getBroadcastItem(i);
16618                    try {
16619                        callback.onPermissionsChanged(uid);
16620                    } catch (RemoteException e) {
16621                        Log.e(TAG, "Permission listener is dead", e);
16622                    }
16623                }
16624            } finally {
16625                mPermissionListeners.finishBroadcast();
16626            }
16627        }
16628    }
16629
16630    private class PackageManagerInternalImpl extends PackageManagerInternal {
16631        @Override
16632        public void setLocationPackagesProvider(PackagesProvider provider) {
16633            synchronized (mPackages) {
16634                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16635            }
16636        }
16637
16638        @Override
16639        public void setImePackagesProvider(PackagesProvider provider) {
16640            synchronized (mPackages) {
16641                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16642            }
16643        }
16644
16645        @Override
16646        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16647            synchronized (mPackages) {
16648                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16649            }
16650        }
16651
16652        @Override
16653        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16654            synchronized (mPackages) {
16655                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16656            }
16657        }
16658
16659        @Override
16660        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16661            synchronized (mPackages) {
16662                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16663            }
16664        }
16665
16666        @Override
16667        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16668            synchronized (mPackages) {
16669                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16670            }
16671        }
16672
16673        @Override
16674        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16675            synchronized (mPackages) {
16676                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16677            }
16678        }
16679
16680        @Override
16681        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16682            synchronized (mPackages) {
16683                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16684                        packageName, userId);
16685            }
16686        }
16687
16688        @Override
16689        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16690            synchronized (mPackages) {
16691                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16692                        packageName, userId);
16693            }
16694        }
16695        @Override
16696        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16697            synchronized (mPackages) {
16698                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16699                        packageName, userId);
16700            }
16701        }
16702    }
16703
16704    @Override
16705    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16706        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16707        synchronized (mPackages) {
16708            final long identity = Binder.clearCallingIdentity();
16709            try {
16710                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16711                        packageNames, userId);
16712            } finally {
16713                Binder.restoreCallingIdentity(identity);
16714            }
16715        }
16716    }
16717
16718    private static void enforceSystemOrPhoneCaller(String tag) {
16719        int callingUid = Binder.getCallingUid();
16720        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16721            throw new SecurityException(
16722                    "Cannot call " + tag + " from UID " + callingUid);
16723        }
16724    }
16725}
16726