PackageManagerService.java revision 60aae166e99dff0dba379e14c0fc43e89fd1a018
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86import android.Manifest;
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IOnPermissionsChangeListener;
108import android.content.pm.IPackageDataObserver;
109import android.content.pm.IPackageDeleteObserver;
110import android.content.pm.IPackageDeleteObserver2;
111import android.content.pm.IPackageInstallObserver2;
112import android.content.pm.IPackageInstaller;
113import android.content.pm.IPackageManager;
114import android.content.pm.IPackageMoveObserver;
115import android.content.pm.IPackageStatsObserver;
116import android.content.pm.InstrumentationInfo;
117import android.content.pm.IntentFilterVerificationInfo;
118import android.content.pm.KeySet;
119import android.content.pm.ManifestDigest;
120import android.content.pm.PackageCleanItem;
121import android.content.pm.PackageInfo;
122import android.content.pm.PackageInfoLite;
123import android.content.pm.PackageInstaller;
124import android.content.pm.PackageManager;
125import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126import android.content.pm.PackageManagerInternal;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageParser.ActivityIntentInfo;
129import android.content.pm.PackageParser.PackageLite;
130import android.content.pm.PackageParser.PackageParserException;
131import android.content.pm.PackageStats;
132import android.content.pm.PackageUserState;
133import android.content.pm.ParceledListSlice;
134import android.content.pm.PermissionGroupInfo;
135import android.content.pm.PermissionInfo;
136import android.content.pm.ProviderInfo;
137import android.content.pm.ResolveInfo;
138import android.content.pm.ServiceInfo;
139import android.content.pm.Signature;
140import android.content.pm.UserInfo;
141import android.content.pm.VerificationParams;
142import android.content.pm.VerifierDeviceIdentity;
143import android.content.pm.VerifierInfo;
144import android.content.res.Resources;
145import android.hardware.display.DisplayManager;
146import android.net.Uri;
147import android.os.Debug;
148import android.os.Binder;
149import android.os.Build;
150import android.os.Bundle;
151import android.os.Environment;
152import android.os.Environment.UserEnvironment;
153import android.os.FileUtils;
154import android.os.Handler;
155import android.os.IBinder;
156import android.os.Looper;
157import android.os.Message;
158import android.os.Parcel;
159import android.os.ParcelFileDescriptor;
160import android.os.Process;
161import android.os.RemoteCallbackList;
162import android.os.RemoteException;
163import android.os.SELinux;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.storage.IMountService;
170import android.os.storage.MountServiceInternal;
171import android.os.storage.StorageEventListener;
172import android.os.storage.StorageManager;
173import android.os.storage.VolumeInfo;
174import android.os.storage.VolumeRecord;
175import android.security.KeyStore;
176import android.security.SystemKeyStore;
177import android.system.ErrnoException;
178import android.system.Os;
179import android.system.StructStat;
180import android.text.TextUtils;
181import android.text.format.DateUtils;
182import android.util.ArrayMap;
183import android.util.ArraySet;
184import android.util.AtomicFile;
185import android.util.DisplayMetrics;
186import android.util.EventLog;
187import android.util.ExceptionUtils;
188import android.util.Log;
189import android.util.LogPrinter;
190import android.util.MathUtils;
191import android.util.PrintStreamPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
196import android.util.Xml;
197import android.view.Display;
198
199import dalvik.system.DexFile;
200import dalvik.system.VMRuntime;
201
202import libcore.io.IoUtils;
203import libcore.util.EmptyArray;
204
205import com.android.internal.R;
206import com.android.internal.annotations.GuardedBy;
207import com.android.internal.app.IMediaContainerService;
208import com.android.internal.app.ResolverActivity;
209import com.android.internal.content.NativeLibraryHelper;
210import com.android.internal.content.PackageHelper;
211import com.android.internal.os.IParcelFileDescriptorFactory;
212import com.android.internal.os.SomeArgs;
213import com.android.internal.os.Zygote;
214import com.android.internal.util.ArrayUtils;
215import com.android.internal.util.FastPrintWriter;
216import com.android.internal.util.FastXmlSerializer;
217import com.android.internal.util.IndentingPrintWriter;
218import com.android.internal.util.Preconditions;
219import com.android.server.EventLogTags;
220import com.android.server.FgThread;
221import com.android.server.IntentResolver;
222import com.android.server.LocalServices;
223import com.android.server.ServiceThread;
224import com.android.server.SystemConfig;
225import com.android.server.Watchdog;
226import com.android.server.pm.PermissionsState.PermissionState;
227import com.android.server.pm.Settings.DatabaseVersion;
228import com.android.server.pm.Settings.VersionInfo;
229import com.android.server.storage.DeviceStorageMonitorInternal;
230
231import org.xmlpull.v1.XmlPullParser;
232import org.xmlpull.v1.XmlPullParserException;
233import org.xmlpull.v1.XmlSerializer;
234
235import java.io.BufferedInputStream;
236import java.io.BufferedOutputStream;
237import java.io.BufferedReader;
238import java.io.ByteArrayInputStream;
239import java.io.ByteArrayOutputStream;
240import java.io.File;
241import java.io.FileDescriptor;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.FileReader;
245import java.io.FilenameFilter;
246import java.io.IOException;
247import java.io.InputStream;
248import java.io.PrintWriter;
249import java.nio.charset.StandardCharsets;
250import java.security.NoSuchAlgorithmException;
251import java.security.PublicKey;
252import java.security.cert.CertificateEncodingException;
253import java.security.cert.CertificateException;
254import java.text.SimpleDateFormat;
255import java.util.ArrayList;
256import java.util.Arrays;
257import java.util.Collection;
258import java.util.Collections;
259import java.util.Comparator;
260import java.util.Date;
261import java.util.Iterator;
262import java.util.List;
263import java.util.Map;
264import java.util.Objects;
265import java.util.Set;
266import java.util.concurrent.CountDownLatch;
267import java.util.concurrent.TimeUnit;
268import java.util.concurrent.atomic.AtomicBoolean;
269import java.util.concurrent.atomic.AtomicInteger;
270import java.util.concurrent.atomic.AtomicLong;
271
272/**
273 * Keep track of all those .apks everywhere.
274 *
275 * This is very central to the platform's security; please run the unit
276 * tests whenever making modifications here:
277 *
278mmm frameworks/base/tests/AndroidTests
279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        // If this is the only one pending we might
1150                        // have to bind to the service again.
1151                        if (!connectToService()) {
1152                            Slog.e(TAG, "Failed to bind to media container service");
1153                            params.serviceError();
1154                            return;
1155                        } else {
1156                            // Once we bind to the service, the first
1157                            // pending request will be processed.
1158                            mPendingInstalls.add(idx, params);
1159                        }
1160                    } else {
1161                        mPendingInstalls.add(idx, params);
1162                        // Already bound to the service. Just make
1163                        // sure we trigger off processing the first request.
1164                        if (idx == 0) {
1165                            mHandler.sendEmptyMessage(MCS_BOUND);
1166                        }
1167                    }
1168                    break;
1169                }
1170                case MCS_BOUND: {
1171                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1172                    if (msg.obj != null) {
1173                        mContainerService = (IMediaContainerService) msg.obj;
1174                    }
1175                    if (mContainerService == null) {
1176                        if (!mBound) {
1177                            // Something seriously wrong since we are not bound and we are not
1178                            // waiting for connection. Bail out.
1179                            Slog.e(TAG, "Cannot bind to media container service");
1180                            for (HandlerParams params : mPendingInstalls) {
1181                                // Indicate service bind error
1182                                params.serviceError();
1183                            }
1184                            mPendingInstalls.clear();
1185                        } else {
1186                            Slog.w(TAG, "Waiting to connect to media container service");
1187                        }
1188                    } else if (mPendingInstalls.size() > 0) {
1189                        HandlerParams params = mPendingInstalls.get(0);
1190                        if (params != null) {
1191                            if (params.startCopy()) {
1192                                // We are done...  look for more work or to
1193                                // go idle.
1194                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1195                                        "Checking for more work or unbind...");
1196                                // Delete pending install
1197                                if (mPendingInstalls.size() > 0) {
1198                                    mPendingInstalls.remove(0);
1199                                }
1200                                if (mPendingInstalls.size() == 0) {
1201                                    if (mBound) {
1202                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                                "Posting delayed MCS_UNBIND");
1204                                        removeMessages(MCS_UNBIND);
1205                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1206                                        // Unbind after a little delay, to avoid
1207                                        // continual thrashing.
1208                                        sendMessageDelayed(ubmsg, 10000);
1209                                    }
1210                                } else {
1211                                    // There are more pending requests in queue.
1212                                    // Just post MCS_BOUND message to trigger processing
1213                                    // of next pending install.
1214                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                            "Posting MCS_BOUND for next work");
1216                                    mHandler.sendEmptyMessage(MCS_BOUND);
1217                                }
1218                            }
1219                        }
1220                    } else {
1221                        // Should never happen ideally.
1222                        Slog.w(TAG, "Empty queue");
1223                    }
1224                    break;
1225                }
1226                case MCS_RECONNECT: {
1227                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1228                    if (mPendingInstalls.size() > 0) {
1229                        if (mBound) {
1230                            disconnectService();
1231                        }
1232                        if (!connectToService()) {
1233                            Slog.e(TAG, "Failed to bind to media container service");
1234                            for (HandlerParams params : mPendingInstalls) {
1235                                // Indicate service bind error
1236                                params.serviceError();
1237                            }
1238                            mPendingInstalls.clear();
1239                        }
1240                    }
1241                    break;
1242                }
1243                case MCS_UNBIND: {
1244                    // If there is no actual work left, then time to unbind.
1245                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1246
1247                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1248                        if (mBound) {
1249                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1250
1251                            disconnectService();
1252                        }
1253                    } else if (mPendingInstalls.size() > 0) {
1254                        // There are more pending requests in queue.
1255                        // Just post MCS_BOUND message to trigger processing
1256                        // of next pending install.
1257                        mHandler.sendEmptyMessage(MCS_BOUND);
1258                    }
1259
1260                    break;
1261                }
1262                case MCS_GIVE_UP: {
1263                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1264                    mPendingInstalls.remove(0);
1265                    break;
1266                }
1267                case SEND_PENDING_BROADCAST: {
1268                    String packages[];
1269                    ArrayList<String> components[];
1270                    int size = 0;
1271                    int uids[];
1272                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1273                    synchronized (mPackages) {
1274                        if (mPendingBroadcasts == null) {
1275                            return;
1276                        }
1277                        size = mPendingBroadcasts.size();
1278                        if (size <= 0) {
1279                            // Nothing to be done. Just return
1280                            return;
1281                        }
1282                        packages = new String[size];
1283                        components = new ArrayList[size];
1284                        uids = new int[size];
1285                        int i = 0;  // filling out the above arrays
1286
1287                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1288                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1289                            Iterator<Map.Entry<String, ArrayList<String>>> it
1290                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1291                                            .entrySet().iterator();
1292                            while (it.hasNext() && i < size) {
1293                                Map.Entry<String, ArrayList<String>> ent = it.next();
1294                                packages[i] = ent.getKey();
1295                                components[i] = ent.getValue();
1296                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1297                                uids[i] = (ps != null)
1298                                        ? UserHandle.getUid(packageUserId, ps.appId)
1299                                        : -1;
1300                                i++;
1301                            }
1302                        }
1303                        size = i;
1304                        mPendingBroadcasts.clear();
1305                    }
1306                    // Send broadcasts
1307                    for (int i = 0; i < size; i++) {
1308                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1309                    }
1310                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1311                    break;
1312                }
1313                case START_CLEANING_PACKAGE: {
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1315                    final String packageName = (String)msg.obj;
1316                    final int userId = msg.arg1;
1317                    final boolean andCode = msg.arg2 != 0;
1318                    synchronized (mPackages) {
1319                        if (userId == UserHandle.USER_ALL) {
1320                            int[] users = sUserManager.getUserIds();
1321                            for (int user : users) {
1322                                mSettings.addPackageToCleanLPw(
1323                                        new PackageCleanItem(user, packageName, andCode));
1324                            }
1325                        } else {
1326                            mSettings.addPackageToCleanLPw(
1327                                    new PackageCleanItem(userId, packageName, andCode));
1328                        }
1329                    }
1330                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1331                    startCleaningPackages();
1332                } break;
1333                case POST_INSTALL: {
1334                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1335                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1336                    mRunningInstalls.delete(msg.arg1);
1337                    boolean deleteOld = false;
1338
1339                    if (data != null) {
1340                        InstallArgs args = data.args;
1341                        PackageInstalledInfo res = data.res;
1342
1343                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1344                            final String packageName = res.pkg.applicationInfo.packageName;
1345                            res.removedInfo.sendBroadcast(false, true, false);
1346                            Bundle extras = new Bundle(1);
1347                            extras.putInt(Intent.EXTRA_UID, res.uid);
1348
1349                            // Now that we successfully installed the package, grant runtime
1350                            // permissions if requested before broadcasting the install.
1351                            if ((args.installFlags
1352                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1353                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1354                                        args.installGrantPermissions);
1355                            }
1356
1357                            // Determine the set of users who are adding this
1358                            // package for the first time vs. those who are seeing
1359                            // an update.
1360                            int[] firstUsers;
1361                            int[] updateUsers = new int[0];
1362                            if (res.origUsers == null || res.origUsers.length == 0) {
1363                                firstUsers = res.newUsers;
1364                            } else {
1365                                firstUsers = new int[0];
1366                                for (int i=0; i<res.newUsers.length; i++) {
1367                                    int user = res.newUsers[i];
1368                                    boolean isNew = true;
1369                                    for (int j=0; j<res.origUsers.length; j++) {
1370                                        if (res.origUsers[j] == user) {
1371                                            isNew = false;
1372                                            break;
1373                                        }
1374                                    }
1375                                    if (isNew) {
1376                                        int[] newFirst = new int[firstUsers.length+1];
1377                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1378                                                firstUsers.length);
1379                                        newFirst[firstUsers.length] = user;
1380                                        firstUsers = newFirst;
1381                                    } else {
1382                                        int[] newUpdate = new int[updateUsers.length+1];
1383                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1384                                                updateUsers.length);
1385                                        newUpdate[updateUsers.length] = user;
1386                                        updateUsers = newUpdate;
1387                                    }
1388                                }
1389                            }
1390                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1391                                    packageName, extras, null, null, firstUsers);
1392                            final boolean update = res.removedInfo.removedPackage != null;
1393                            if (update) {
1394                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1395                            }
1396                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1397                                    packageName, extras, null, null, updateUsers);
1398                            if (update) {
1399                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1400                                        packageName, extras, null, null, updateUsers);
1401                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1402                                        null, null, packageName, null, updateUsers);
1403
1404                                // treat asec-hosted packages like removable media on upgrade
1405                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1406                                    if (DEBUG_INSTALL) {
1407                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1408                                                + " is ASEC-hosted -> AVAILABLE");
1409                                    }
1410                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1411                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1412                                    pkgList.add(packageName);
1413                                    sendResourcesChangedBroadcast(true, true,
1414                                            pkgList,uidArray, null);
1415                                }
1416                            }
1417                            if (res.removedInfo.args != null) {
1418                                // Remove the replaced package's older resources safely now
1419                                deleteOld = true;
1420                            }
1421
1422                            // If this app is a browser and it's newly-installed for some
1423                            // users, clear any default-browser state in those users
1424                            if (firstUsers.length > 0) {
1425                                // the app's nature doesn't depend on the user, so we can just
1426                                // check its browser nature in any user and generalize.
1427                                if (packageIsBrowser(packageName, firstUsers[0])) {
1428                                    synchronized (mPackages) {
1429                                        for (int userId : firstUsers) {
1430                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1431                                        }
1432                                    }
1433                                }
1434                            }
1435                            // Log current value of "unknown sources" setting
1436                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1437                                getUnknownSourcesSettings());
1438                        }
1439                        // Force a gc to clear up things
1440                        Runtime.getRuntime().gc();
1441                        // We delete after a gc for applications  on sdcard.
1442                        if (deleteOld) {
1443                            synchronized (mInstallLock) {
1444                                res.removedInfo.args.doPostDeleteLI(true);
1445                            }
1446                        }
1447                        if (args.observer != null) {
1448                            try {
1449                                Bundle extras = extrasForInstallResult(res);
1450                                args.observer.onPackageInstalled(res.name, res.returnCode,
1451                                        res.returnMsg, extras);
1452                            } catch (RemoteException e) {
1453                                Slog.i(TAG, "Observer no longer exists.");
1454                            }
1455                        }
1456                    } else {
1457                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1458                    }
1459                } break;
1460                case UPDATED_MEDIA_STATUS: {
1461                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1462                    boolean reportStatus = msg.arg1 == 1;
1463                    boolean doGc = msg.arg2 == 1;
1464                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1465                    if (doGc) {
1466                        // Force a gc to clear up stale containers.
1467                        Runtime.getRuntime().gc();
1468                    }
1469                    if (msg.obj != null) {
1470                        @SuppressWarnings("unchecked")
1471                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1472                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1473                        // Unload containers
1474                        unloadAllContainers(args);
1475                    }
1476                    if (reportStatus) {
1477                        try {
1478                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1479                            PackageHelper.getMountService().finishMediaUpdate();
1480                        } catch (RemoteException e) {
1481                            Log.e(TAG, "MountService not running?");
1482                        }
1483                    }
1484                } break;
1485                case WRITE_SETTINGS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_SETTINGS);
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        mSettings.writeLPr();
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case WRITE_PACKAGE_RESTRICTIONS: {
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1497                    synchronized (mPackages) {
1498                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1499                        for (int userId : mDirtyUsers) {
1500                            mSettings.writePackageRestrictionsLPr(userId);
1501                        }
1502                        mDirtyUsers.clear();
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                } break;
1506                case CHECK_PENDING_VERIFICATION: {
1507                    final int verificationId = msg.arg1;
1508                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1509
1510                    if ((state != null) && !state.timeoutExtended()) {
1511                        final InstallArgs args = state.getInstallArgs();
1512                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1513
1514                        Slog.i(TAG, "Verification timed out for " + originUri);
1515                        mPendingVerification.remove(verificationId);
1516
1517                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518
1519                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1520                            Slog.i(TAG, "Continuing with installation of " + originUri);
1521                            state.setVerifierResponse(Binder.getCallingUid(),
1522                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_ALLOW,
1525                                    state.getInstallArgs().getUser());
1526                            try {
1527                                ret = args.copyApk(mContainerService, true);
1528                            } catch (RemoteException e) {
1529                                Slog.e(TAG, "Could not contact the ContainerService");
1530                            }
1531                        } else {
1532                            broadcastPackageVerified(verificationId, originUri,
1533                                    PackageManager.VERIFICATION_REJECT,
1534                                    state.getInstallArgs().getUser());
1535                        }
1536
1537                        processPendingInstall(args, ret);
1538                        mHandler.sendEmptyMessage(MCS_UNBIND);
1539                    }
1540                    break;
1541                }
1542                case PACKAGE_VERIFIED: {
1543                    final int verificationId = msg.arg1;
1544
1545                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1546                    if (state == null) {
1547                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1548                        break;
1549                    }
1550
1551                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1552
1553                    state.setVerifierResponse(response.callerUid, response.code);
1554
1555                    if (state.isVerificationComplete()) {
1556                        mPendingVerification.remove(verificationId);
1557
1558                        final InstallArgs args = state.getInstallArgs();
1559                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1560
1561                        int ret;
1562                        if (state.isInstallAllowed()) {
1563                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    response.code, state.getInstallArgs().getUser());
1566                            try {
1567                                ret = args.copyApk(mContainerService, true);
1568                            } catch (RemoteException e) {
1569                                Slog.e(TAG, "Could not contact the ContainerService");
1570                            }
1571                        } else {
1572                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1573                        }
1574
1575                        processPendingInstall(args, ret);
1576
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579
1580                    break;
1581                }
1582                case START_INTENT_FILTER_VERIFICATIONS: {
1583                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1584                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1585                            params.replacing, params.pkg);
1586                    break;
1587                }
1588                case INTENT_FILTER_VERIFIED: {
1589                    final int verificationId = msg.arg1;
1590
1591                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1592                            verificationId);
1593                    if (state == null) {
1594                        Slog.w(TAG, "Invalid IntentFilter verification token "
1595                                + verificationId + " received");
1596                        break;
1597                    }
1598
1599                    final int userId = state.getUserId();
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "Processing IntentFilter verification with token:"
1603                            + verificationId + " and userId:" + userId);
1604
1605                    final IntentFilterVerificationResponse response =
1606                            (IntentFilterVerificationResponse) msg.obj;
1607
1608                    state.setVerifierResponse(response.callerUid, response.code);
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "IntentFilter verification with token:" + verificationId
1612                            + " and userId:" + userId
1613                            + " is settings verifier response with response code:"
1614                            + response.code);
1615
1616                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1618                                + response.getFailedDomainsString());
1619                    }
1620
1621                    if (state.isVerificationComplete()) {
1622                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1623                    } else {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                                "IntentFilter verification with token:" + verificationId
1626                                + " was not said to be complete");
1627                    }
1628
1629                    break;
1630                }
1631            }
1632        }
1633    }
1634
1635    private StorageEventListener mStorageListener = new StorageEventListener() {
1636        @Override
1637        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1638            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1639                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1640                    final String volumeUuid = vol.getFsUuid();
1641
1642                    // Clean up any users or apps that were removed or recreated
1643                    // while this volume was missing
1644                    reconcileUsers(volumeUuid);
1645                    reconcileApps(volumeUuid);
1646
1647                    // Clean up any install sessions that expired or were
1648                    // cancelled while this volume was missing
1649                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1650
1651                    loadPrivatePackages(vol);
1652
1653                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1654                    unloadPrivatePackages(vol);
1655                }
1656            }
1657
1658            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1659                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1660                    updateExternalMediaStatus(true, false);
1661                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1662                    updateExternalMediaStatus(false, false);
1663                }
1664            }
1665        }
1666
1667        @Override
1668        public void onVolumeForgotten(String fsUuid) {
1669            if (TextUtils.isEmpty(fsUuid)) {
1670                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1671                return;
1672            }
1673
1674            // Remove any apps installed on the forgotten volume
1675            synchronized (mPackages) {
1676                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1677                for (PackageSetting ps : packages) {
1678                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1679                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1680                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1681                }
1682
1683                mSettings.onVolumeForgotten(fsUuid);
1684                mSettings.writeLPr();
1685            }
1686        }
1687    };
1688
1689    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1690            String[] grantedPermissions) {
1691        if (userId >= UserHandle.USER_OWNER) {
1692            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1693        } else if (userId == UserHandle.USER_ALL) {
1694            final int[] userIds;
1695            synchronized (mPackages) {
1696                userIds = UserManagerService.getInstance().getUserIds();
1697            }
1698            for (int someUserId : userIds) {
1699                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1700            }
1701        }
1702
1703        // We could have touched GID membership, so flush out packages.list
1704        synchronized (mPackages) {
1705            mSettings.writePackageListLPr();
1706        }
1707    }
1708
1709    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1710            String[] grantedPermissions) {
1711        SettingBase sb = (SettingBase) pkg.mExtras;
1712        if (sb == null) {
1713            return;
1714        }
1715
1716        PermissionsState permissionsState = sb.getPermissionsState();
1717
1718        for (String permission : pkg.requestedPermissions) {
1719            BasePermission bp = mSettings.mPermissions.get(permission);
1720            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1721                    || ArrayUtils.contains(grantedPermissions, permission))) {
1722                permissionsState.grantRuntimePermission(bp, userId);
1723            }
1724        }
1725    }
1726
1727    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1728        Bundle extras = null;
1729        switch (res.returnCode) {
1730            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1731                extras = new Bundle();
1732                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1733                        res.origPermission);
1734                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1735                        res.origPackage);
1736                break;
1737            }
1738            case PackageManager.INSTALL_SUCCEEDED: {
1739                extras = new Bundle();
1740                extras.putBoolean(Intent.EXTRA_REPLACING,
1741                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1742                break;
1743            }
1744        }
1745        return extras;
1746    }
1747
1748    void scheduleWriteSettingsLocked() {
1749        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1750            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1751        }
1752    }
1753
1754    void scheduleWritePackageRestrictionsLocked(int userId) {
1755        if (!sUserManager.exists(userId)) return;
1756        mDirtyUsers.add(userId);
1757        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1758            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1759        }
1760    }
1761
1762    public static PackageManagerService main(Context context, Installer installer,
1763            boolean factoryTest, boolean onlyCore) {
1764        PackageManagerService m = new PackageManagerService(context, installer,
1765                factoryTest, onlyCore);
1766        ServiceManager.addService("package", m);
1767        return m;
1768    }
1769
1770    static String[] splitString(String str, char sep) {
1771        int count = 1;
1772        int i = 0;
1773        while ((i=str.indexOf(sep, i)) >= 0) {
1774            count++;
1775            i++;
1776        }
1777
1778        String[] res = new String[count];
1779        i=0;
1780        count = 0;
1781        int lastI=0;
1782        while ((i=str.indexOf(sep, i)) >= 0) {
1783            res[count] = str.substring(lastI, i);
1784            count++;
1785            i++;
1786            lastI = i;
1787        }
1788        res[count] = str.substring(lastI, str.length());
1789        return res;
1790    }
1791
1792    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1793        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1794                Context.DISPLAY_SERVICE);
1795        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1796    }
1797
1798    public PackageManagerService(Context context, Installer installer,
1799            boolean factoryTest, boolean onlyCore) {
1800        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1801                SystemClock.uptimeMillis());
1802
1803        if (mSdkVersion <= 0) {
1804            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1805        }
1806
1807        mContext = context;
1808        mFactoryTest = factoryTest;
1809        mOnlyCore = onlyCore;
1810        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1811        mMetrics = new DisplayMetrics();
1812        mSettings = new Settings(mPackages);
1813        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1814                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1815        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1816                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1817        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1818                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1819        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1820                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1821        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1822                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1823        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1824                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1825
1826        // TODO: add a property to control this?
1827        long dexOptLRUThresholdInMinutes;
1828        if (mLazyDexOpt) {
1829            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1830        } else {
1831            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1832        }
1833        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1834
1835        String separateProcesses = SystemProperties.get("debug.separate_processes");
1836        if (separateProcesses != null && separateProcesses.length() > 0) {
1837            if ("*".equals(separateProcesses)) {
1838                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1839                mSeparateProcesses = null;
1840                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1841            } else {
1842                mDefParseFlags = 0;
1843                mSeparateProcesses = separateProcesses.split(",");
1844                Slog.w(TAG, "Running with debug.separate_processes: "
1845                        + separateProcesses);
1846            }
1847        } else {
1848            mDefParseFlags = 0;
1849            mSeparateProcesses = null;
1850        }
1851
1852        mInstaller = installer;
1853        mPackageDexOptimizer = new PackageDexOptimizer(this);
1854        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1855
1856        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1857                FgThread.get().getLooper());
1858
1859        getDefaultDisplayMetrics(context, mMetrics);
1860
1861        SystemConfig systemConfig = SystemConfig.getInstance();
1862        mGlobalGids = systemConfig.getGlobalGids();
1863        mSystemPermissions = systemConfig.getSystemPermissions();
1864        mAvailableFeatures = systemConfig.getAvailableFeatures();
1865
1866        synchronized (mInstallLock) {
1867        // writer
1868        synchronized (mPackages) {
1869            mHandlerThread = new ServiceThread(TAG,
1870                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1871            mHandlerThread.start();
1872            mHandler = new PackageHandler(mHandlerThread.getLooper());
1873            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1874
1875            File dataDir = Environment.getDataDirectory();
1876            mAppDataDir = new File(dataDir, "data");
1877            mAppInstallDir = new File(dataDir, "app");
1878            mAppLib32InstallDir = new File(dataDir, "app-lib");
1879            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1880            mUserAppDataDir = new File(dataDir, "user");
1881            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1882
1883            sUserManager = new UserManagerService(context, this,
1884                    mInstallLock, mPackages);
1885
1886            // Propagate permission configuration in to package manager.
1887            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1888                    = systemConfig.getPermissions();
1889            for (int i=0; i<permConfig.size(); i++) {
1890                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1891                BasePermission bp = mSettings.mPermissions.get(perm.name);
1892                if (bp == null) {
1893                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1894                    mSettings.mPermissions.put(perm.name, bp);
1895                }
1896                if (perm.gids != null) {
1897                    bp.setGids(perm.gids, perm.perUser);
1898                }
1899            }
1900
1901            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1902            for (int i=0; i<libConfig.size(); i++) {
1903                mSharedLibraries.put(libConfig.keyAt(i),
1904                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1905            }
1906
1907            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1908
1909            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1910                    mSdkVersion, mOnlyCore);
1911
1912            String customResolverActivity = Resources.getSystem().getString(
1913                    R.string.config_customResolverActivity);
1914            if (TextUtils.isEmpty(customResolverActivity)) {
1915                customResolverActivity = null;
1916            } else {
1917                mCustomResolverComponentName = ComponentName.unflattenFromString(
1918                        customResolverActivity);
1919            }
1920
1921            long startTime = SystemClock.uptimeMillis();
1922
1923            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1924                    startTime);
1925
1926            // Set flag to monitor and not change apk file paths when
1927            // scanning install directories.
1928            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1929
1930            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1931
1932            /**
1933             * Add everything in the in the boot class path to the
1934             * list of process files because dexopt will have been run
1935             * if necessary during zygote startup.
1936             */
1937            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1938            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1939
1940            if (bootClassPath != null) {
1941                String[] bootClassPathElements = splitString(bootClassPath, ':');
1942                for (String element : bootClassPathElements) {
1943                    alreadyDexOpted.add(element);
1944                }
1945            } else {
1946                Slog.w(TAG, "No BOOTCLASSPATH found!");
1947            }
1948
1949            if (systemServerClassPath != null) {
1950                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1951                for (String element : systemServerClassPathElements) {
1952                    alreadyDexOpted.add(element);
1953                }
1954            } else {
1955                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1956            }
1957
1958            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1959            final String[] dexCodeInstructionSets =
1960                    getDexCodeInstructionSets(
1961                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1962
1963            /**
1964             * Ensure all external libraries have had dexopt run on them.
1965             */
1966            if (mSharedLibraries.size() > 0) {
1967                // NOTE: For now, we're compiling these system "shared libraries"
1968                // (and framework jars) into all available architectures. It's possible
1969                // to compile them only when we come across an app that uses them (there's
1970                // already logic for that in scanPackageLI) but that adds some complexity.
1971                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1972                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1973                        final String lib = libEntry.path;
1974                        if (lib == null) {
1975                            continue;
1976                        }
1977
1978                        try {
1979                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1980                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1981                                alreadyDexOpted.add(lib);
1982                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1983                            }
1984                        } catch (FileNotFoundException e) {
1985                            Slog.w(TAG, "Library not found: " + lib);
1986                        } catch (IOException e) {
1987                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1988                                    + e.getMessage());
1989                        }
1990                    }
1991                }
1992            }
1993
1994            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1995
1996            // Gross hack for now: we know this file doesn't contain any
1997            // code, so don't dexopt it to avoid the resulting log spew.
1998            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1999
2000            // Gross hack for now: we know this file is only part of
2001            // the boot class path for art, so don't dexopt it to
2002            // avoid the resulting log spew.
2003            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2004
2005            /**
2006             * There are a number of commands implemented in Java, which
2007             * we currently need to do the dexopt on so that they can be
2008             * run from a non-root shell.
2009             */
2010            String[] frameworkFiles = frameworkDir.list();
2011            if (frameworkFiles != null) {
2012                // TODO: We could compile these only for the most preferred ABI. We should
2013                // first double check that the dex files for these commands are not referenced
2014                // by other system apps.
2015                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2016                    for (int i=0; i<frameworkFiles.length; i++) {
2017                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2018                        String path = libPath.getPath();
2019                        // Skip the file if we already did it.
2020                        if (alreadyDexOpted.contains(path)) {
2021                            continue;
2022                        }
2023                        // Skip the file if it is not a type we want to dexopt.
2024                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2025                            continue;
2026                        }
2027                        try {
2028                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2029                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2030                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2031                            }
2032                        } catch (FileNotFoundException e) {
2033                            Slog.w(TAG, "Jar not found: " + path);
2034                        } catch (IOException e) {
2035                            Slog.w(TAG, "Exception reading jar: " + path, e);
2036                        }
2037                    }
2038                }
2039            }
2040
2041            final VersionInfo ver = mSettings.getInternalVersion();
2042            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2043            // when upgrading from pre-M, promote system app permissions from install to runtime
2044            mPromoteSystemApps =
2045                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2046
2047            // save off the names of pre-existing system packages prior to scanning; we don't
2048            // want to automatically grant runtime permissions for new system apps
2049            if (mPromoteSystemApps) {
2050                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2051                while (pkgSettingIter.hasNext()) {
2052                    PackageSetting ps = pkgSettingIter.next();
2053                    if (isSystemApp(ps)) {
2054                        mExistingSystemPackages.add(ps.name);
2055                    }
2056                }
2057            }
2058
2059            // Collect vendor overlay packages.
2060            // (Do this before scanning any apps.)
2061            // For security and version matching reason, only consider
2062            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2063            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2064            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2065                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2066
2067            // Find base frameworks (resource packages without code).
2068            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2069                    | PackageParser.PARSE_IS_SYSTEM_DIR
2070                    | PackageParser.PARSE_IS_PRIVILEGED,
2071                    scanFlags | SCAN_NO_DEX, 0);
2072
2073            // Collected privileged system packages.
2074            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2075            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2076                    | PackageParser.PARSE_IS_SYSTEM_DIR
2077                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2078
2079            // Collect ordinary system packages.
2080            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2081            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2082                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2083
2084            // Collect all vendor packages.
2085            File vendorAppDir = new File("/vendor/app");
2086            try {
2087                vendorAppDir = vendorAppDir.getCanonicalFile();
2088            } catch (IOException e) {
2089                // failed to look up canonical path, continue with original one
2090            }
2091            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2092                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2093
2094            // Collect all OEM packages.
2095            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2096            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2097                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2098
2099            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2100            mInstaller.moveFiles();
2101
2102            // Prune any system packages that no longer exist.
2103            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2104            if (!mOnlyCore) {
2105                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2106                while (psit.hasNext()) {
2107                    PackageSetting ps = psit.next();
2108
2109                    /*
2110                     * If this is not a system app, it can't be a
2111                     * disable system app.
2112                     */
2113                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2114                        continue;
2115                    }
2116
2117                    /*
2118                     * If the package is scanned, it's not erased.
2119                     */
2120                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2121                    if (scannedPkg != null) {
2122                        /*
2123                         * If the system app is both scanned and in the
2124                         * disabled packages list, then it must have been
2125                         * added via OTA. Remove it from the currently
2126                         * scanned package so the previously user-installed
2127                         * application can be scanned.
2128                         */
2129                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2130                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2131                                    + ps.name + "; removing system app.  Last known codePath="
2132                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2133                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2134                                    + scannedPkg.mVersionCode);
2135                            removePackageLI(ps, true);
2136                            mExpectingBetter.put(ps.name, ps.codePath);
2137                        }
2138
2139                        continue;
2140                    }
2141
2142                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2143                        psit.remove();
2144                        logCriticalInfo(Log.WARN, "System package " + ps.name
2145                                + " no longer exists; wiping its data");
2146                        removeDataDirsLI(null, ps.name);
2147                    } else {
2148                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2149                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2150                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2151                        }
2152                    }
2153                }
2154            }
2155
2156            //look for any incomplete package installations
2157            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2158            //clean up list
2159            for(int i = 0; i < deletePkgsList.size(); i++) {
2160                //clean up here
2161                cleanupInstallFailedPackage(deletePkgsList.get(i));
2162            }
2163            //delete tmp files
2164            deleteTempPackageFiles();
2165
2166            // Remove any shared userIDs that have no associated packages
2167            mSettings.pruneSharedUsersLPw();
2168
2169            if (!mOnlyCore) {
2170                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2171                        SystemClock.uptimeMillis());
2172                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2173
2174                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2175                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2176
2177                /**
2178                 * Remove disable package settings for any updated system
2179                 * apps that were removed via an OTA. If they're not a
2180                 * previously-updated app, remove them completely.
2181                 * Otherwise, just revoke their system-level permissions.
2182                 */
2183                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2184                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2185                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2186
2187                    String msg;
2188                    if (deletedPkg == null) {
2189                        msg = "Updated system package " + deletedAppName
2190                                + " no longer exists; wiping its data";
2191                        removeDataDirsLI(null, deletedAppName);
2192                    } else {
2193                        msg = "Updated system app + " + deletedAppName
2194                                + " no longer present; removing system privileges for "
2195                                + deletedAppName;
2196
2197                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2198
2199                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2200                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2201                    }
2202                    logCriticalInfo(Log.WARN, msg);
2203                }
2204
2205                /**
2206                 * Make sure all system apps that we expected to appear on
2207                 * the userdata partition actually showed up. If they never
2208                 * appeared, crawl back and revive the system version.
2209                 */
2210                for (int i = 0; i < mExpectingBetter.size(); i++) {
2211                    final String packageName = mExpectingBetter.keyAt(i);
2212                    if (!mPackages.containsKey(packageName)) {
2213                        final File scanFile = mExpectingBetter.valueAt(i);
2214
2215                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2216                                + " but never showed up; reverting to system");
2217
2218                        final int reparseFlags;
2219                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2220                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2221                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2222                                    | PackageParser.PARSE_IS_PRIVILEGED;
2223                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2224                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2225                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2226                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2227                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2228                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2229                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2230                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2231                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2232                        } else {
2233                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2234                            continue;
2235                        }
2236
2237                        mSettings.enableSystemPackageLPw(packageName);
2238
2239                        try {
2240                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2241                        } catch (PackageManagerException e) {
2242                            Slog.e(TAG, "Failed to parse original system package: "
2243                                    + e.getMessage());
2244                        }
2245                    }
2246                }
2247            }
2248            mExpectingBetter.clear();
2249
2250            // Now that we know all of the shared libraries, update all clients to have
2251            // the correct library paths.
2252            updateAllSharedLibrariesLPw();
2253
2254            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2255                // NOTE: We ignore potential failures here during a system scan (like
2256                // the rest of the commands above) because there's precious little we
2257                // can do about it. A settings error is reported, though.
2258                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2259                        false /* force dexopt */, false /* defer dexopt */);
2260            }
2261
2262            // Now that we know all the packages we are keeping,
2263            // read and update their last usage times.
2264            mPackageUsage.readLP();
2265
2266            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2267                    SystemClock.uptimeMillis());
2268            Slog.i(TAG, "Time to scan packages: "
2269                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2270                    + " seconds");
2271
2272            // If the platform SDK has changed since the last time we booted,
2273            // we need to re-grant app permission to catch any new ones that
2274            // appear.  This is really a hack, and means that apps can in some
2275            // cases get permissions that the user didn't initially explicitly
2276            // allow...  it would be nice to have some better way to handle
2277            // this situation.
2278            int updateFlags = UPDATE_PERMISSIONS_ALL;
2279            if (ver.sdkVersion != mSdkVersion) {
2280                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2281                        + mSdkVersion + "; regranting permissions for internal storage");
2282                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2283            }
2284            updatePermissionsLPw(null, null, updateFlags);
2285            ver.sdkVersion = mSdkVersion;
2286
2287            // If this is the first boot or an update from pre-M, and it is a normal
2288            // boot, then we need to initialize the default preferred apps across
2289            // all defined users.
2290            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2291                for (UserInfo user : sUserManager.getUsers(true)) {
2292                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2293                    applyFactoryDefaultBrowserLPw(user.id);
2294                    primeDomainVerificationsLPw(user.id);
2295                }
2296            }
2297
2298            // If this is first boot after an OTA, and a normal boot, then
2299            // we need to clear code cache directories.
2300            if (mIsUpgrade && !onlyCore) {
2301                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2302                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2303                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2304                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2305                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2306                    }
2307                }
2308                ver.fingerprint = Build.FINGERPRINT;
2309            }
2310
2311            checkDefaultBrowser();
2312
2313            // clear only after permissions and other defaults have been updated
2314            mExistingSystemPackages.clear();
2315            mPromoteSystemApps = false;
2316
2317            // All the changes are done during package scanning.
2318            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2319
2320            // can downgrade to reader
2321            mSettings.writeLPr();
2322
2323            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2324                    SystemClock.uptimeMillis());
2325
2326            mRequiredVerifierPackage = getRequiredVerifierLPr();
2327            mRequiredInstallerPackage = getRequiredInstallerLPr();
2328
2329            mInstallerService = new PackageInstallerService(context, this);
2330
2331            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2332            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2333                    mIntentFilterVerifierComponent);
2334
2335        } // synchronized (mPackages)
2336        } // synchronized (mInstallLock)
2337
2338        // Now after opening every single application zip, make sure they
2339        // are all flushed.  Not really needed, but keeps things nice and
2340        // tidy.
2341        Runtime.getRuntime().gc();
2342
2343        // Expose private service for system components to use.
2344        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2345    }
2346
2347    @Override
2348    public boolean isFirstBoot() {
2349        return !mRestoredSettings;
2350    }
2351
2352    @Override
2353    public boolean isOnlyCoreApps() {
2354        return mOnlyCore;
2355    }
2356
2357    @Override
2358    public boolean isUpgrade() {
2359        return mIsUpgrade;
2360    }
2361
2362    private String getRequiredVerifierLPr() {
2363        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2364        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2365                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2366
2367        String requiredVerifier = null;
2368
2369        final int N = receivers.size();
2370        for (int i = 0; i < N; i++) {
2371            final ResolveInfo info = receivers.get(i);
2372
2373            if (info.activityInfo == null) {
2374                continue;
2375            }
2376
2377            final String packageName = info.activityInfo.packageName;
2378
2379            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2380                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2381                continue;
2382            }
2383
2384            if (requiredVerifier != null) {
2385                throw new RuntimeException("There can be only one required verifier");
2386            }
2387
2388            requiredVerifier = packageName;
2389        }
2390
2391        return requiredVerifier;
2392    }
2393
2394    private String getRequiredInstallerLPr() {
2395        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2396        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2397        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2398
2399        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2400                PACKAGE_MIME_TYPE, 0, 0);
2401
2402        String requiredInstaller = null;
2403
2404        final int N = installers.size();
2405        for (int i = 0; i < N; i++) {
2406            final ResolveInfo info = installers.get(i);
2407            final String packageName = info.activityInfo.packageName;
2408
2409            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2410                continue;
2411            }
2412
2413            if (requiredInstaller != null) {
2414                throw new RuntimeException("There must be one required installer");
2415            }
2416
2417            requiredInstaller = packageName;
2418        }
2419
2420        if (requiredInstaller == null) {
2421            throw new RuntimeException("There must be one required installer");
2422        }
2423
2424        return requiredInstaller;
2425    }
2426
2427    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2428        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2429        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2430                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2431
2432        ComponentName verifierComponentName = null;
2433
2434        int priority = -1000;
2435        final int N = receivers.size();
2436        for (int i = 0; i < N; i++) {
2437            final ResolveInfo info = receivers.get(i);
2438
2439            if (info.activityInfo == null) {
2440                continue;
2441            }
2442
2443            final String packageName = info.activityInfo.packageName;
2444
2445            final PackageSetting ps = mSettings.mPackages.get(packageName);
2446            if (ps == null) {
2447                continue;
2448            }
2449
2450            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2451                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2452                continue;
2453            }
2454
2455            // Select the IntentFilterVerifier with the highest priority
2456            if (priority < info.priority) {
2457                priority = info.priority;
2458                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2459                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2460                        + verifierComponentName + " with priority: " + info.priority);
2461            }
2462        }
2463
2464        return verifierComponentName;
2465    }
2466
2467    private void primeDomainVerificationsLPw(int userId) {
2468        if (DEBUG_DOMAIN_VERIFICATION) {
2469            Slog.d(TAG, "Priming domain verifications in user " + userId);
2470        }
2471
2472        SystemConfig systemConfig = SystemConfig.getInstance();
2473        ArraySet<String> packages = systemConfig.getLinkedApps();
2474        ArraySet<String> domains = new ArraySet<String>();
2475
2476        for (String packageName : packages) {
2477            PackageParser.Package pkg = mPackages.get(packageName);
2478            if (pkg != null) {
2479                if (!pkg.isSystemApp()) {
2480                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2481                    continue;
2482                }
2483
2484                domains.clear();
2485                for (PackageParser.Activity a : pkg.activities) {
2486                    for (ActivityIntentInfo filter : a.intents) {
2487                        if (hasValidDomains(filter)) {
2488                            domains.addAll(filter.getHostsList());
2489                        }
2490                    }
2491                }
2492
2493                if (domains.size() > 0) {
2494                    if (DEBUG_DOMAIN_VERIFICATION) {
2495                        Slog.v(TAG, "      + " + packageName);
2496                    }
2497                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2498                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2499                    // and then 'always' in the per-user state actually used for intent resolution.
2500                    final IntentFilterVerificationInfo ivi;
2501                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2502                            new ArrayList<String>(domains));
2503                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2504                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2505                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2506                } else {
2507                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2508                            + "' does not handle web links");
2509                }
2510            } else {
2511                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2512            }
2513        }
2514
2515        scheduleWritePackageRestrictionsLocked(userId);
2516        scheduleWriteSettingsLocked();
2517    }
2518
2519    private void applyFactoryDefaultBrowserLPw(int userId) {
2520        // The default browser app's package name is stored in a string resource,
2521        // with a product-specific overlay used for vendor customization.
2522        String browserPkg = mContext.getResources().getString(
2523                com.android.internal.R.string.default_browser);
2524        if (!TextUtils.isEmpty(browserPkg)) {
2525            // non-empty string => required to be a known package
2526            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2527            if (ps == null) {
2528                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2529                browserPkg = null;
2530            } else {
2531                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2532            }
2533        }
2534
2535        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2536        // default.  If there's more than one, just leave everything alone.
2537        if (browserPkg == null) {
2538            calculateDefaultBrowserLPw(userId);
2539        }
2540    }
2541
2542    private void calculateDefaultBrowserLPw(int userId) {
2543        List<String> allBrowsers = resolveAllBrowserApps(userId);
2544        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2545        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2546    }
2547
2548    private List<String> resolveAllBrowserApps(int userId) {
2549        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2550        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2551                PackageManager.MATCH_ALL, userId);
2552
2553        final int count = list.size();
2554        List<String> result = new ArrayList<String>(count);
2555        for (int i=0; i<count; i++) {
2556            ResolveInfo info = list.get(i);
2557            if (info.activityInfo == null
2558                    || !info.handleAllWebDataURI
2559                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2560                    || result.contains(info.activityInfo.packageName)) {
2561                continue;
2562            }
2563            result.add(info.activityInfo.packageName);
2564        }
2565
2566        return result;
2567    }
2568
2569    private boolean packageIsBrowser(String packageName, int userId) {
2570        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2571                PackageManager.MATCH_ALL, userId);
2572        final int N = list.size();
2573        for (int i = 0; i < N; i++) {
2574            ResolveInfo info = list.get(i);
2575            if (packageName.equals(info.activityInfo.packageName)) {
2576                return true;
2577            }
2578        }
2579        return false;
2580    }
2581
2582    private void checkDefaultBrowser() {
2583        final int myUserId = UserHandle.myUserId();
2584        final String packageName = getDefaultBrowserPackageName(myUserId);
2585        if (packageName != null) {
2586            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2587            if (info == null) {
2588                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2589                synchronized (mPackages) {
2590                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2591                }
2592            }
2593        }
2594    }
2595
2596    @Override
2597    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2598            throws RemoteException {
2599        try {
2600            return super.onTransact(code, data, reply, flags);
2601        } catch (RuntimeException e) {
2602            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2603                Slog.wtf(TAG, "Package Manager Crash", e);
2604            }
2605            throw e;
2606        }
2607    }
2608
2609    void cleanupInstallFailedPackage(PackageSetting ps) {
2610        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2611
2612        removeDataDirsLI(ps.volumeUuid, ps.name);
2613        if (ps.codePath != null) {
2614            if (ps.codePath.isDirectory()) {
2615                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2616            } else {
2617                ps.codePath.delete();
2618            }
2619        }
2620        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2621            if (ps.resourcePath.isDirectory()) {
2622                FileUtils.deleteContents(ps.resourcePath);
2623            }
2624            ps.resourcePath.delete();
2625        }
2626        mSettings.removePackageLPw(ps.name);
2627    }
2628
2629    static int[] appendInts(int[] cur, int[] add) {
2630        if (add == null) return cur;
2631        if (cur == null) return add;
2632        final int N = add.length;
2633        for (int i=0; i<N; i++) {
2634            cur = appendInt(cur, add[i]);
2635        }
2636        return cur;
2637    }
2638
2639    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        final PackageSetting ps = (PackageSetting) p.mExtras;
2642        if (ps == null) {
2643            return null;
2644        }
2645
2646        final PermissionsState permissionsState = ps.getPermissionsState();
2647
2648        final int[] gids = permissionsState.computeGids(userId);
2649        final Set<String> permissions = permissionsState.getPermissions(userId);
2650        final PackageUserState state = ps.readUserState(userId);
2651
2652        return PackageParser.generatePackageInfo(p, gids, flags,
2653                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2654    }
2655
2656    @Override
2657    public boolean isPackageFrozen(String packageName) {
2658        synchronized (mPackages) {
2659            final PackageSetting ps = mSettings.mPackages.get(packageName);
2660            if (ps != null) {
2661                return ps.frozen;
2662            }
2663        }
2664        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2665        return true;
2666    }
2667
2668    @Override
2669    public boolean isPackageAvailable(String packageName, int userId) {
2670        if (!sUserManager.exists(userId)) return false;
2671        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2672        synchronized (mPackages) {
2673            PackageParser.Package p = mPackages.get(packageName);
2674            if (p != null) {
2675                final PackageSetting ps = (PackageSetting) p.mExtras;
2676                if (ps != null) {
2677                    final PackageUserState state = ps.readUserState(userId);
2678                    if (state != null) {
2679                        return PackageParser.isAvailable(state);
2680                    }
2681                }
2682            }
2683        }
2684        return false;
2685    }
2686
2687    @Override
2688    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2689        if (!sUserManager.exists(userId)) return null;
2690        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2691        // reader
2692        synchronized (mPackages) {
2693            PackageParser.Package p = mPackages.get(packageName);
2694            if (DEBUG_PACKAGE_INFO)
2695                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2696            if (p != null) {
2697                return generatePackageInfo(p, flags, userId);
2698            }
2699            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2700                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public String[] currentToCanonicalPackageNames(String[] names) {
2708        String[] out = new String[names.length];
2709        // reader
2710        synchronized (mPackages) {
2711            for (int i=names.length-1; i>=0; i--) {
2712                PackageSetting ps = mSettings.mPackages.get(names[i]);
2713                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2714            }
2715        }
2716        return out;
2717    }
2718
2719    @Override
2720    public String[] canonicalToCurrentPackageNames(String[] names) {
2721        String[] out = new String[names.length];
2722        // reader
2723        synchronized (mPackages) {
2724            for (int i=names.length-1; i>=0; i--) {
2725                String cur = mSettings.mRenamedPackages.get(names[i]);
2726                out[i] = cur != null ? cur : names[i];
2727            }
2728        }
2729        return out;
2730    }
2731
2732    @Override
2733    public int getPackageUid(String packageName, int userId) {
2734        if (!sUserManager.exists(userId)) return -1;
2735        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2736
2737        // reader
2738        synchronized (mPackages) {
2739            PackageParser.Package p = mPackages.get(packageName);
2740            if(p != null) {
2741                return UserHandle.getUid(userId, p.applicationInfo.uid);
2742            }
2743            PackageSetting ps = mSettings.mPackages.get(packageName);
2744            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2745                return -1;
2746            }
2747            p = ps.pkg;
2748            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2749        }
2750    }
2751
2752    @Override
2753    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2754        if (!sUserManager.exists(userId)) {
2755            return null;
2756        }
2757
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2759                "getPackageGids");
2760
2761        // reader
2762        synchronized (mPackages) {
2763            PackageParser.Package p = mPackages.get(packageName);
2764            if (DEBUG_PACKAGE_INFO) {
2765                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2766            }
2767            if (p != null) {
2768                PackageSetting ps = (PackageSetting) p.mExtras;
2769                return ps.getPermissionsState().computeGids(userId);
2770            }
2771        }
2772
2773        return null;
2774    }
2775
2776    static PermissionInfo generatePermissionInfo(
2777            BasePermission bp, int flags) {
2778        if (bp.perm != null) {
2779            return PackageParser.generatePermissionInfo(bp.perm, flags);
2780        }
2781        PermissionInfo pi = new PermissionInfo();
2782        pi.name = bp.name;
2783        pi.packageName = bp.sourcePackage;
2784        pi.nonLocalizedLabel = bp.name;
2785        pi.protectionLevel = bp.protectionLevel;
2786        return pi;
2787    }
2788
2789    @Override
2790    public PermissionInfo getPermissionInfo(String name, int flags) {
2791        // reader
2792        synchronized (mPackages) {
2793            final BasePermission p = mSettings.mPermissions.get(name);
2794            if (p != null) {
2795                return generatePermissionInfo(p, flags);
2796            }
2797            return null;
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2806            for (BasePermission p : mSettings.mPermissions.values()) {
2807                if (group == null) {
2808                    if (p.perm == null || p.perm.info.group == null) {
2809                        out.add(generatePermissionInfo(p, flags));
2810                    }
2811                } else {
2812                    if (p.perm != null && group.equals(p.perm.info.group)) {
2813                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2814                    }
2815                }
2816            }
2817
2818            if (out.size() > 0) {
2819                return out;
2820            }
2821            return mPermissionGroups.containsKey(group) ? out : null;
2822        }
2823    }
2824
2825    @Override
2826    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2827        // reader
2828        synchronized (mPackages) {
2829            return PackageParser.generatePermissionGroupInfo(
2830                    mPermissionGroups.get(name), flags);
2831        }
2832    }
2833
2834    @Override
2835    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2836        // reader
2837        synchronized (mPackages) {
2838            final int N = mPermissionGroups.size();
2839            ArrayList<PermissionGroupInfo> out
2840                    = new ArrayList<PermissionGroupInfo>(N);
2841            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2842                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2843            }
2844            return out;
2845        }
2846    }
2847
2848    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2849            int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        PackageSetting ps = mSettings.mPackages.get(packageName);
2852        if (ps != null) {
2853            if (ps.pkg == null) {
2854                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2855                        flags, userId);
2856                if (pInfo != null) {
2857                    return pInfo.applicationInfo;
2858                }
2859                return null;
2860            }
2861            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2862                    ps.readUserState(userId), userId);
2863        }
2864        return null;
2865    }
2866
2867    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2868            int userId) {
2869        if (!sUserManager.exists(userId)) return null;
2870        PackageSetting ps = mSettings.mPackages.get(packageName);
2871        if (ps != null) {
2872            PackageParser.Package pkg = ps.pkg;
2873            if (pkg == null) {
2874                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2875                    return null;
2876                }
2877                // Only data remains, so we aren't worried about code paths
2878                pkg = new PackageParser.Package(packageName);
2879                pkg.applicationInfo.packageName = packageName;
2880                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2881                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2882                pkg.applicationInfo.dataDir = Environment
2883                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2884                        .getAbsolutePath();
2885                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2886                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2887            }
2888            return generatePackageInfo(pkg, flags, userId);
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2895        if (!sUserManager.exists(userId)) return null;
2896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2897        // writer
2898        synchronized (mPackages) {
2899            PackageParser.Package p = mPackages.get(packageName);
2900            if (DEBUG_PACKAGE_INFO) Log.v(
2901                    TAG, "getApplicationInfo " + packageName
2902                    + ": " + p);
2903            if (p != null) {
2904                PackageSetting ps = mSettings.mPackages.get(packageName);
2905                if (ps == null) return null;
2906                // Note: isEnabledLP() does not apply here - always return info
2907                return PackageParser.generateApplicationInfo(
2908                        p, flags, ps.readUserState(userId), userId);
2909            }
2910            if ("android".equals(packageName)||"system".equals(packageName)) {
2911                return mAndroidApplication;
2912            }
2913            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2914                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2915            }
2916        }
2917        return null;
2918    }
2919
2920    @Override
2921    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2922            final IPackageDataObserver observer) {
2923        mContext.enforceCallingOrSelfPermission(
2924                android.Manifest.permission.CLEAR_APP_CACHE, null);
2925        // Queue up an async operation since clearing cache may take a little while.
2926        mHandler.post(new Runnable() {
2927            public void run() {
2928                mHandler.removeCallbacks(this);
2929                int retCode = -1;
2930                synchronized (mInstallLock) {
2931                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2932                    if (retCode < 0) {
2933                        Slog.w(TAG, "Couldn't clear application caches");
2934                    }
2935                }
2936                if (observer != null) {
2937                    try {
2938                        observer.onRemoveCompleted(null, (retCode >= 0));
2939                    } catch (RemoteException e) {
2940                        Slog.w(TAG, "RemoveException when invoking call back");
2941                    }
2942                }
2943            }
2944        });
2945    }
2946
2947    @Override
2948    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2949            final IntentSender pi) {
2950        mContext.enforceCallingOrSelfPermission(
2951                android.Manifest.permission.CLEAR_APP_CACHE, null);
2952        // Queue up an async operation since clearing cache may take a little while.
2953        mHandler.post(new Runnable() {
2954            public void run() {
2955                mHandler.removeCallbacks(this);
2956                int retCode = -1;
2957                synchronized (mInstallLock) {
2958                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2959                    if (retCode < 0) {
2960                        Slog.w(TAG, "Couldn't clear application caches");
2961                    }
2962                }
2963                if(pi != null) {
2964                    try {
2965                        // Callback via pending intent
2966                        int code = (retCode >= 0) ? 1 : 0;
2967                        pi.sendIntent(null, code, null,
2968                                null, null);
2969                    } catch (SendIntentException e1) {
2970                        Slog.i(TAG, "Failed to send pending intent");
2971                    }
2972                }
2973            }
2974        });
2975    }
2976
2977    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2978        synchronized (mInstallLock) {
2979            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2980                throw new IOException("Failed to free enough space");
2981            }
2982        }
2983    }
2984
2985    @Override
2986    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2987        if (!sUserManager.exists(userId)) return null;
2988        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2989        synchronized (mPackages) {
2990            PackageParser.Activity a = mActivities.mActivities.get(component);
2991
2992            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2993            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2994                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2995                if (ps == null) return null;
2996                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2997                        userId);
2998            }
2999            if (mResolveComponentName.equals(component)) {
3000                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3001                        new PackageUserState(), userId);
3002            }
3003        }
3004        return null;
3005    }
3006
3007    @Override
3008    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3009            String resolvedType) {
3010        synchronized (mPackages) {
3011            if (component.equals(mResolveComponentName)) {
3012                // The resolver supports EVERYTHING!
3013                return true;
3014            }
3015            PackageParser.Activity a = mActivities.mActivities.get(component);
3016            if (a == null) {
3017                return false;
3018            }
3019            for (int i=0; i<a.intents.size(); i++) {
3020                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3021                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3022                    return true;
3023                }
3024            }
3025            return false;
3026        }
3027    }
3028
3029    @Override
3030    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3031        if (!sUserManager.exists(userId)) return null;
3032        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3033        synchronized (mPackages) {
3034            PackageParser.Activity a = mReceivers.mActivities.get(component);
3035            if (DEBUG_PACKAGE_INFO) Log.v(
3036                TAG, "getReceiverInfo " + component + ": " + a);
3037            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3038                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3039                if (ps == null) return null;
3040                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3041                        userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3049        if (!sUserManager.exists(userId)) return null;
3050        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3051        synchronized (mPackages) {
3052            PackageParser.Service s = mServices.mServices.get(component);
3053            if (DEBUG_PACKAGE_INFO) Log.v(
3054                TAG, "getServiceInfo " + component + ": " + s);
3055            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3056                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3057                if (ps == null) return null;
3058                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3059                        userId);
3060            }
3061        }
3062        return null;
3063    }
3064
3065    @Override
3066    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3067        if (!sUserManager.exists(userId)) return null;
3068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3069        synchronized (mPackages) {
3070            PackageParser.Provider p = mProviders.mProviders.get(component);
3071            if (DEBUG_PACKAGE_INFO) Log.v(
3072                TAG, "getProviderInfo " + component + ": " + p);
3073            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3074                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3075                if (ps == null) return null;
3076                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3077                        userId);
3078            }
3079        }
3080        return null;
3081    }
3082
3083    @Override
3084    public String[] getSystemSharedLibraryNames() {
3085        Set<String> libSet;
3086        synchronized (mPackages) {
3087            libSet = mSharedLibraries.keySet();
3088            int size = libSet.size();
3089            if (size > 0) {
3090                String[] libs = new String[size];
3091                libSet.toArray(libs);
3092                return libs;
3093            }
3094        }
3095        return null;
3096    }
3097
3098    /**
3099     * @hide
3100     */
3101    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3102        synchronized (mPackages) {
3103            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3104            if (lib != null && lib.apk != null) {
3105                return mPackages.get(lib.apk);
3106            }
3107        }
3108        return null;
3109    }
3110
3111    @Override
3112    public FeatureInfo[] getSystemAvailableFeatures() {
3113        Collection<FeatureInfo> featSet;
3114        synchronized (mPackages) {
3115            featSet = mAvailableFeatures.values();
3116            int size = featSet.size();
3117            if (size > 0) {
3118                FeatureInfo[] features = new FeatureInfo[size+1];
3119                featSet.toArray(features);
3120                FeatureInfo fi = new FeatureInfo();
3121                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3122                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3123                features[size] = fi;
3124                return features;
3125            }
3126        }
3127        return null;
3128    }
3129
3130    @Override
3131    public boolean hasSystemFeature(String name) {
3132        synchronized (mPackages) {
3133            return mAvailableFeatures.containsKey(name);
3134        }
3135    }
3136
3137    private void checkValidCaller(int uid, int userId) {
3138        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3139            return;
3140
3141        throw new SecurityException("Caller uid=" + uid
3142                + " is not privileged to communicate with user=" + userId);
3143    }
3144
3145    @Override
3146    public int checkPermission(String permName, String pkgName, int userId) {
3147        if (!sUserManager.exists(userId)) {
3148            return PackageManager.PERMISSION_DENIED;
3149        }
3150
3151        synchronized (mPackages) {
3152            final PackageParser.Package p = mPackages.get(pkgName);
3153            if (p != null && p.mExtras != null) {
3154                final PackageSetting ps = (PackageSetting) p.mExtras;
3155                final PermissionsState permissionsState = ps.getPermissionsState();
3156                if (permissionsState.hasPermission(permName, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3160                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3161                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3162                    return PackageManager.PERMISSION_GRANTED;
3163                }
3164            }
3165        }
3166
3167        return PackageManager.PERMISSION_DENIED;
3168    }
3169
3170    @Override
3171    public int checkUidPermission(String permName, int uid) {
3172        final int userId = UserHandle.getUserId(uid);
3173
3174        if (!sUserManager.exists(userId)) {
3175            return PackageManager.PERMISSION_DENIED;
3176        }
3177
3178        synchronized (mPackages) {
3179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3180            if (obj != null) {
3181                final SettingBase ps = (SettingBase) obj;
3182                final PermissionsState permissionsState = ps.getPermissionsState();
3183                if (permissionsState.hasPermission(permName, userId)) {
3184                    return PackageManager.PERMISSION_GRANTED;
3185                }
3186                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3187                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3188                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3189                    return PackageManager.PERMISSION_GRANTED;
3190                }
3191            } else {
3192                ArraySet<String> perms = mSystemPermissions.get(uid);
3193                if (perms != null) {
3194                    if (perms.contains(permName)) {
3195                        return PackageManager.PERMISSION_GRANTED;
3196                    }
3197                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3198                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3199                        return PackageManager.PERMISSION_GRANTED;
3200                    }
3201                }
3202            }
3203        }
3204
3205        return PackageManager.PERMISSION_DENIED;
3206    }
3207
3208    @Override
3209    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3210        if (UserHandle.getCallingUserId() != userId) {
3211            mContext.enforceCallingPermission(
3212                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3213                    "isPermissionRevokedByPolicy for user " + userId);
3214        }
3215
3216        if (checkPermission(permission, packageName, userId)
3217                == PackageManager.PERMISSION_GRANTED) {
3218            return false;
3219        }
3220
3221        final long identity = Binder.clearCallingIdentity();
3222        try {
3223            final int flags = getPermissionFlags(permission, packageName, userId);
3224            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3225        } finally {
3226            Binder.restoreCallingIdentity(identity);
3227        }
3228    }
3229
3230    @Override
3231    public String getPermissionControllerPackageName() {
3232        synchronized (mPackages) {
3233            return mRequiredInstallerPackage;
3234        }
3235    }
3236
3237    /**
3238     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3239     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3240     * @param checkShell TODO(yamasani):
3241     * @param message the message to log on security exception
3242     */
3243    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3244            boolean checkShell, String message) {
3245        if (userId < 0) {
3246            throw new IllegalArgumentException("Invalid userId " + userId);
3247        }
3248        if (checkShell) {
3249            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3250        }
3251        if (userId == UserHandle.getUserId(callingUid)) return;
3252        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3253            if (requireFullPermission) {
3254                mContext.enforceCallingOrSelfPermission(
3255                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3256            } else {
3257                try {
3258                    mContext.enforceCallingOrSelfPermission(
3259                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3260                } catch (SecurityException se) {
3261                    mContext.enforceCallingOrSelfPermission(
3262                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3263                }
3264            }
3265        }
3266    }
3267
3268    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3269        if (callingUid == Process.SHELL_UID) {
3270            if (userHandle >= 0
3271                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3272                throw new SecurityException("Shell does not have permission to access user "
3273                        + userHandle);
3274            } else if (userHandle < 0) {
3275                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3276                        + Debug.getCallers(3));
3277            }
3278        }
3279    }
3280
3281    private BasePermission findPermissionTreeLP(String permName) {
3282        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3283            if (permName.startsWith(bp.name) &&
3284                    permName.length() > bp.name.length() &&
3285                    permName.charAt(bp.name.length()) == '.') {
3286                return bp;
3287            }
3288        }
3289        return null;
3290    }
3291
3292    private BasePermission checkPermissionTreeLP(String permName) {
3293        if (permName != null) {
3294            BasePermission bp = findPermissionTreeLP(permName);
3295            if (bp != null) {
3296                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3297                    return bp;
3298                }
3299                throw new SecurityException("Calling uid "
3300                        + Binder.getCallingUid()
3301                        + " is not allowed to add to permission tree "
3302                        + bp.name + " owned by uid " + bp.uid);
3303            }
3304        }
3305        throw new SecurityException("No permission tree found for " + permName);
3306    }
3307
3308    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3309        if (s1 == null) {
3310            return s2 == null;
3311        }
3312        if (s2 == null) {
3313            return false;
3314        }
3315        if (s1.getClass() != s2.getClass()) {
3316            return false;
3317        }
3318        return s1.equals(s2);
3319    }
3320
3321    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3322        if (pi1.icon != pi2.icon) return false;
3323        if (pi1.logo != pi2.logo) return false;
3324        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3325        if (!compareStrings(pi1.name, pi2.name)) return false;
3326        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3327        // We'll take care of setting this one.
3328        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3329        // These are not currently stored in settings.
3330        //if (!compareStrings(pi1.group, pi2.group)) return false;
3331        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3332        //if (pi1.labelRes != pi2.labelRes) return false;
3333        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3334        return true;
3335    }
3336
3337    int permissionInfoFootprint(PermissionInfo info) {
3338        int size = info.name.length();
3339        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3340        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3341        return size;
3342    }
3343
3344    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3345        int size = 0;
3346        for (BasePermission perm : mSettings.mPermissions.values()) {
3347            if (perm.uid == tree.uid) {
3348                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3349            }
3350        }
3351        return size;
3352    }
3353
3354    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3355        // We calculate the max size of permissions defined by this uid and throw
3356        // if that plus the size of 'info' would exceed our stated maximum.
3357        if (tree.uid != Process.SYSTEM_UID) {
3358            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3359            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3360                throw new SecurityException("Permission tree size cap exceeded");
3361            }
3362        }
3363    }
3364
3365    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3366        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3367            throw new SecurityException("Label must be specified in permission");
3368        }
3369        BasePermission tree = checkPermissionTreeLP(info.name);
3370        BasePermission bp = mSettings.mPermissions.get(info.name);
3371        boolean added = bp == null;
3372        boolean changed = true;
3373        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3374        if (added) {
3375            enforcePermissionCapLocked(info, tree);
3376            bp = new BasePermission(info.name, tree.sourcePackage,
3377                    BasePermission.TYPE_DYNAMIC);
3378        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3379            throw new SecurityException(
3380                    "Not allowed to modify non-dynamic permission "
3381                    + info.name);
3382        } else {
3383            if (bp.protectionLevel == fixedLevel
3384                    && bp.perm.owner.equals(tree.perm.owner)
3385                    && bp.uid == tree.uid
3386                    && comparePermissionInfos(bp.perm.info, info)) {
3387                changed = false;
3388            }
3389        }
3390        bp.protectionLevel = fixedLevel;
3391        info = new PermissionInfo(info);
3392        info.protectionLevel = fixedLevel;
3393        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3394        bp.perm.info.packageName = tree.perm.info.packageName;
3395        bp.uid = tree.uid;
3396        if (added) {
3397            mSettings.mPermissions.put(info.name, bp);
3398        }
3399        if (changed) {
3400            if (!async) {
3401                mSettings.writeLPr();
3402            } else {
3403                scheduleWriteSettingsLocked();
3404            }
3405        }
3406        return added;
3407    }
3408
3409    @Override
3410    public boolean addPermission(PermissionInfo info) {
3411        synchronized (mPackages) {
3412            return addPermissionLocked(info, false);
3413        }
3414    }
3415
3416    @Override
3417    public boolean addPermissionAsync(PermissionInfo info) {
3418        synchronized (mPackages) {
3419            return addPermissionLocked(info, true);
3420        }
3421    }
3422
3423    @Override
3424    public void removePermission(String name) {
3425        synchronized (mPackages) {
3426            checkPermissionTreeLP(name);
3427            BasePermission bp = mSettings.mPermissions.get(name);
3428            if (bp != null) {
3429                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3430                    throw new SecurityException(
3431                            "Not allowed to modify non-dynamic permission "
3432                            + name);
3433                }
3434                mSettings.mPermissions.remove(name);
3435                mSettings.writeLPr();
3436            }
3437        }
3438    }
3439
3440    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3441            BasePermission bp) {
3442        int index = pkg.requestedPermissions.indexOf(bp.name);
3443        if (index == -1) {
3444            throw new SecurityException("Package " + pkg.packageName
3445                    + " has not requested permission " + bp.name);
3446        }
3447        if (!bp.isRuntime() && !bp.isDevelopment()) {
3448            throw new SecurityException("Permission " + bp.name
3449                    + " is not a changeable permission type");
3450        }
3451    }
3452
3453    @Override
3454    public void grantRuntimePermission(String packageName, String name, final int userId) {
3455        if (!sUserManager.exists(userId)) {
3456            Log.e(TAG, "No such user:" + userId);
3457            return;
3458        }
3459
3460        mContext.enforceCallingOrSelfPermission(
3461                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3462                "grantRuntimePermission");
3463
3464        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3465                "grantRuntimePermission");
3466
3467        final int uid;
3468        final SettingBase sb;
3469
3470        synchronized (mPackages) {
3471            final PackageParser.Package pkg = mPackages.get(packageName);
3472            if (pkg == null) {
3473                throw new IllegalArgumentException("Unknown package: " + packageName);
3474            }
3475
3476            final BasePermission bp = mSettings.mPermissions.get(name);
3477            if (bp == null) {
3478                throw new IllegalArgumentException("Unknown permission: " + name);
3479            }
3480
3481            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3482
3483            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3484            sb = (SettingBase) pkg.mExtras;
3485            if (sb == null) {
3486                throw new IllegalArgumentException("Unknown package: " + packageName);
3487            }
3488
3489            final PermissionsState permissionsState = sb.getPermissionsState();
3490
3491            final int flags = permissionsState.getPermissionFlags(name, userId);
3492            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3493                throw new SecurityException("Cannot grant system fixed permission: "
3494                        + name + " for package: " + packageName);
3495            }
3496
3497            if (bp.isDevelopment()) {
3498                // Development permissions must be handled specially, since they are not
3499                // normal runtime permissions.  For now they apply to all users.
3500                if (permissionsState.grantInstallPermission(bp) !=
3501                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3502                    scheduleWriteSettingsLocked();
3503                }
3504                return;
3505            }
3506
3507            final int result = permissionsState.grantRuntimePermission(bp, userId);
3508            switch (result) {
3509                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3510                    return;
3511                }
3512
3513                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3514                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3515                    mHandler.post(new Runnable() {
3516                        @Override
3517                        public void run() {
3518                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3519                        }
3520                    });
3521                } break;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3525
3526            // Not critical if that is lost - app has to request again.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3528        }
3529
3530        // Only need to do this if user is initialized. Otherwise it's a new user
3531        // and there are no processes running as the user yet and there's no need
3532        // to make an expensive call to remount processes for the changed permissions.
3533        if (READ_EXTERNAL_STORAGE.equals(name)
3534                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3535            final long token = Binder.clearCallingIdentity();
3536            try {
3537                if (sUserManager.isInitialized(userId)) {
3538                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3539                            MountServiceInternal.class);
3540                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3541                }
3542            } finally {
3543                Binder.restoreCallingIdentity(token);
3544            }
3545        }
3546    }
3547
3548    @Override
3549    public void revokeRuntimePermission(String packageName, String name, int userId) {
3550        if (!sUserManager.exists(userId)) {
3551            Log.e(TAG, "No such user:" + userId);
3552            return;
3553        }
3554
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3557                "revokeRuntimePermission");
3558
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3560                "revokeRuntimePermission");
3561
3562        final int appId;
3563
3564        synchronized (mPackages) {
3565            final PackageParser.Package pkg = mPackages.get(packageName);
3566            if (pkg == null) {
3567                throw new IllegalArgumentException("Unknown package: " + packageName);
3568            }
3569
3570            final BasePermission bp = mSettings.mPermissions.get(name);
3571            if (bp == null) {
3572                throw new IllegalArgumentException("Unknown permission: " + name);
3573            }
3574
3575            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3576
3577            SettingBase sb = (SettingBase) pkg.mExtras;
3578            if (sb == null) {
3579                throw new IllegalArgumentException("Unknown package: " + packageName);
3580            }
3581
3582            final PermissionsState permissionsState = sb.getPermissionsState();
3583
3584            final int flags = permissionsState.getPermissionFlags(name, userId);
3585            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3586                throw new SecurityException("Cannot revoke system fixed permission: "
3587                        + name + " for package: " + packageName);
3588            }
3589
3590            if (bp.isDevelopment()) {
3591                // Development permissions must be handled specially, since they are not
3592                // normal runtime permissions.  For now they apply to all users.
3593                if (permissionsState.revokeInstallPermission(bp) !=
3594                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3595                    scheduleWriteSettingsLocked();
3596                }
3597                return;
3598            }
3599
3600            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3601                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3602                return;
3603            }
3604
3605            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3606
3607            // Critical, after this call app should never have the permission.
3608            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3609
3610            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3611        }
3612
3613        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3614    }
3615
3616    @Override
3617    public void resetRuntimePermissions() {
3618        mContext.enforceCallingOrSelfPermission(
3619                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3620                "revokeRuntimePermission");
3621
3622        int callingUid = Binder.getCallingUid();
3623        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3624            mContext.enforceCallingOrSelfPermission(
3625                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3626                    "resetRuntimePermissions");
3627        }
3628
3629        synchronized (mPackages) {
3630            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3631            for (int userId : UserManagerService.getInstance().getUserIds()) {
3632                final int packageCount = mPackages.size();
3633                for (int i = 0; i < packageCount; i++) {
3634                    PackageParser.Package pkg = mPackages.valueAt(i);
3635                    if (!(pkg.mExtras instanceof PackageSetting)) {
3636                        continue;
3637                    }
3638                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3639                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3640                }
3641            }
3642        }
3643    }
3644
3645    @Override
3646    public int getPermissionFlags(String name, String packageName, int userId) {
3647        if (!sUserManager.exists(userId)) {
3648            return 0;
3649        }
3650
3651        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3652
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3654                "getPermissionFlags");
3655
3656        synchronized (mPackages) {
3657            final PackageParser.Package pkg = mPackages.get(packageName);
3658            if (pkg == null) {
3659                throw new IllegalArgumentException("Unknown package: " + packageName);
3660            }
3661
3662            final BasePermission bp = mSettings.mPermissions.get(name);
3663            if (bp == null) {
3664                throw new IllegalArgumentException("Unknown permission: " + name);
3665            }
3666
3667            SettingBase sb = (SettingBase) pkg.mExtras;
3668            if (sb == null) {
3669                throw new IllegalArgumentException("Unknown package: " + packageName);
3670            }
3671
3672            PermissionsState permissionsState = sb.getPermissionsState();
3673            return permissionsState.getPermissionFlags(name, userId);
3674        }
3675    }
3676
3677    @Override
3678    public void updatePermissionFlags(String name, String packageName, int flagMask,
3679            int flagValues, int userId) {
3680        if (!sUserManager.exists(userId)) {
3681            return;
3682        }
3683
3684        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3685
3686        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3687                "updatePermissionFlags");
3688
3689        // Only the system can change these flags and nothing else.
3690        if (getCallingUid() != Process.SYSTEM_UID) {
3691            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3692            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3694            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695        }
3696
3697        synchronized (mPackages) {
3698            final PackageParser.Package pkg = mPackages.get(packageName);
3699            if (pkg == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp == null) {
3705                throw new IllegalArgumentException("Unknown permission: " + name);
3706            }
3707
3708            SettingBase sb = (SettingBase) pkg.mExtras;
3709            if (sb == null) {
3710                throw new IllegalArgumentException("Unknown package: " + packageName);
3711            }
3712
3713            PermissionsState permissionsState = sb.getPermissionsState();
3714
3715            // Only the package manager can change flags for system component permissions.
3716            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3717            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3718                return;
3719            }
3720
3721            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3722
3723            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3724                // Install and runtime permissions are stored in different places,
3725                // so figure out what permission changed and persist the change.
3726                if (permissionsState.getInstallPermissionState(name) != null) {
3727                    scheduleWriteSettingsLocked();
3728                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3729                        || hadState) {
3730                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3731                }
3732            }
3733        }
3734    }
3735
3736    /**
3737     * Update the permission flags for all packages and runtime permissions of a user in order
3738     * to allow device or profile owner to remove POLICY_FIXED.
3739     */
3740    @Override
3741    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3742        if (!sUserManager.exists(userId)) {
3743            return;
3744        }
3745
3746        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3747
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3749                "updatePermissionFlagsForAllApps");
3750
3751        // Only the system can change system fixed flags.
3752        if (getCallingUid() != Process.SYSTEM_UID) {
3753            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3754            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755        }
3756
3757        synchronized (mPackages) {
3758            boolean changed = false;
3759            final int packageCount = mPackages.size();
3760            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3761                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3762                SettingBase sb = (SettingBase) pkg.mExtras;
3763                if (sb == null) {
3764                    continue;
3765                }
3766                PermissionsState permissionsState = sb.getPermissionsState();
3767                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3768                        userId, flagMask, flagValues);
3769            }
3770            if (changed) {
3771                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3772            }
3773        }
3774    }
3775
3776    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3777        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3778                != PackageManager.PERMISSION_GRANTED
3779            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3780                != PackageManager.PERMISSION_GRANTED) {
3781            throw new SecurityException(message + " requires "
3782                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3783                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3784        }
3785    }
3786
3787    @Override
3788    public boolean shouldShowRequestPermissionRationale(String permissionName,
3789            String packageName, int userId) {
3790        if (UserHandle.getCallingUserId() != userId) {
3791            mContext.enforceCallingPermission(
3792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793                    "canShowRequestPermissionRationale for user " + userId);
3794        }
3795
3796        final int uid = getPackageUid(packageName, userId);
3797        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3798            return false;
3799        }
3800
3801        if (checkPermission(permissionName, packageName, userId)
3802                == PackageManager.PERMISSION_GRANTED) {
3803            return false;
3804        }
3805
3806        final int flags;
3807
3808        final long identity = Binder.clearCallingIdentity();
3809        try {
3810            flags = getPermissionFlags(permissionName,
3811                    packageName, userId);
3812        } finally {
3813            Binder.restoreCallingIdentity(identity);
3814        }
3815
3816        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3817                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3818                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3819
3820        if ((flags & fixedFlags) != 0) {
3821            return false;
3822        }
3823
3824        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3825    }
3826
3827    @Override
3828    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3829        mContext.enforceCallingOrSelfPermission(
3830                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3831                "addOnPermissionsChangeListener");
3832
3833        synchronized (mPackages) {
3834            mOnPermissionChangeListeners.addListenerLocked(listener);
3835        }
3836    }
3837
3838    @Override
3839    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3840        synchronized (mPackages) {
3841            mOnPermissionChangeListeners.removeListenerLocked(listener);
3842        }
3843    }
3844
3845    @Override
3846    public boolean isProtectedBroadcast(String actionName) {
3847        synchronized (mPackages) {
3848            return mProtectedBroadcasts.contains(actionName);
3849        }
3850    }
3851
3852    @Override
3853    public int checkSignatures(String pkg1, String pkg2) {
3854        synchronized (mPackages) {
3855            final PackageParser.Package p1 = mPackages.get(pkg1);
3856            final PackageParser.Package p2 = mPackages.get(pkg2);
3857            if (p1 == null || p1.mExtras == null
3858                    || p2 == null || p2.mExtras == null) {
3859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3860            }
3861            return compareSignatures(p1.mSignatures, p2.mSignatures);
3862        }
3863    }
3864
3865    @Override
3866    public int checkUidSignatures(int uid1, int uid2) {
3867        // Map to base uids.
3868        uid1 = UserHandle.getAppId(uid1);
3869        uid2 = UserHandle.getAppId(uid2);
3870        // reader
3871        synchronized (mPackages) {
3872            Signature[] s1;
3873            Signature[] s2;
3874            Object obj = mSettings.getUserIdLPr(uid1);
3875            if (obj != null) {
3876                if (obj instanceof SharedUserSetting) {
3877                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3878                } else if (obj instanceof PackageSetting) {
3879                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3880                } else {
3881                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3882                }
3883            } else {
3884                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885            }
3886            obj = mSettings.getUserIdLPr(uid2);
3887            if (obj != null) {
3888                if (obj instanceof SharedUserSetting) {
3889                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3890                } else if (obj instanceof PackageSetting) {
3891                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3892                } else {
3893                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3894                }
3895            } else {
3896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897            }
3898            return compareSignatures(s1, s2);
3899        }
3900    }
3901
3902    private void killUid(int appId, int userId, String reason) {
3903        final long identity = Binder.clearCallingIdentity();
3904        try {
3905            IActivityManager am = ActivityManagerNative.getDefault();
3906            if (am != null) {
3907                try {
3908                    am.killUid(appId, userId, reason);
3909                } catch (RemoteException e) {
3910                    /* ignore - same process */
3911                }
3912            }
3913        } finally {
3914            Binder.restoreCallingIdentity(identity);
3915        }
3916    }
3917
3918    /**
3919     * Compares two sets of signatures. Returns:
3920     * <br />
3921     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3922     * <br />
3923     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3926     * <br />
3927     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3928     * <br />
3929     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3930     */
3931    static int compareSignatures(Signature[] s1, Signature[] s2) {
3932        if (s1 == null) {
3933            return s2 == null
3934                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3935                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3936        }
3937
3938        if (s2 == null) {
3939            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3940        }
3941
3942        if (s1.length != s2.length) {
3943            return PackageManager.SIGNATURE_NO_MATCH;
3944        }
3945
3946        // Since both signature sets are of size 1, we can compare without HashSets.
3947        if (s1.length == 1) {
3948            return s1[0].equals(s2[0]) ?
3949                    PackageManager.SIGNATURE_MATCH :
3950                    PackageManager.SIGNATURE_NO_MATCH;
3951        }
3952
3953        ArraySet<Signature> set1 = new ArraySet<Signature>();
3954        for (Signature sig : s1) {
3955            set1.add(sig);
3956        }
3957        ArraySet<Signature> set2 = new ArraySet<Signature>();
3958        for (Signature sig : s2) {
3959            set2.add(sig);
3960        }
3961        // Make sure s2 contains all signatures in s1.
3962        if (set1.equals(set2)) {
3963            return PackageManager.SIGNATURE_MATCH;
3964        }
3965        return PackageManager.SIGNATURE_NO_MATCH;
3966    }
3967
3968    /**
3969     * If the database version for this type of package (internal storage or
3970     * external storage) is less than the version where package signatures
3971     * were updated, return true.
3972     */
3973    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3974        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3975        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3976    }
3977
3978    /**
3979     * Used for backward compatibility to make sure any packages with
3980     * certificate chains get upgraded to the new style. {@code existingSigs}
3981     * will be in the old format (since they were stored on disk from before the
3982     * system upgrade) and {@code scannedSigs} will be in the newer format.
3983     */
3984    private int compareSignaturesCompat(PackageSignatures existingSigs,
3985            PackageParser.Package scannedPkg) {
3986        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3987            return PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3991        for (Signature sig : existingSigs.mSignatures) {
3992            existingSet.add(sig);
3993        }
3994        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3995        for (Signature sig : scannedPkg.mSignatures) {
3996            try {
3997                Signature[] chainSignatures = sig.getChainSignatures();
3998                for (Signature chainSig : chainSignatures) {
3999                    scannedCompatSet.add(chainSig);
4000                }
4001            } catch (CertificateEncodingException e) {
4002                scannedCompatSet.add(sig);
4003            }
4004        }
4005        /*
4006         * Make sure the expanded scanned set contains all signatures in the
4007         * existing one.
4008         */
4009        if (scannedCompatSet.equals(existingSet)) {
4010            // Migrate the old signatures to the new scheme.
4011            existingSigs.assignSignatures(scannedPkg.mSignatures);
4012            // The new KeySets will be re-added later in the scanning process.
4013            synchronized (mPackages) {
4014                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4015            }
4016            return PackageManager.SIGNATURE_MATCH;
4017        }
4018        return PackageManager.SIGNATURE_NO_MATCH;
4019    }
4020
4021    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4022        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4023        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4024    }
4025
4026    private int compareSignaturesRecover(PackageSignatures existingSigs,
4027            PackageParser.Package scannedPkg) {
4028        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4029            return PackageManager.SIGNATURE_NO_MATCH;
4030        }
4031
4032        String msg = null;
4033        try {
4034            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4035                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4036                        + scannedPkg.packageName);
4037                return PackageManager.SIGNATURE_MATCH;
4038            }
4039        } catch (CertificateException e) {
4040            msg = e.getMessage();
4041        }
4042
4043        logCriticalInfo(Log.INFO,
4044                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4045        return PackageManager.SIGNATURE_NO_MATCH;
4046    }
4047
4048    @Override
4049    public String[] getPackagesForUid(int uid) {
4050        uid = UserHandle.getAppId(uid);
4051        // reader
4052        synchronized (mPackages) {
4053            Object obj = mSettings.getUserIdLPr(uid);
4054            if (obj instanceof SharedUserSetting) {
4055                final SharedUserSetting sus = (SharedUserSetting) obj;
4056                final int N = sus.packages.size();
4057                final String[] res = new String[N];
4058                final Iterator<PackageSetting> it = sus.packages.iterator();
4059                int i = 0;
4060                while (it.hasNext()) {
4061                    res[i++] = it.next().name;
4062                }
4063                return res;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return new String[] { ps.name };
4067            }
4068        }
4069        return null;
4070    }
4071
4072    @Override
4073    public String getNameForUid(int uid) {
4074        // reader
4075        synchronized (mPackages) {
4076            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4077            if (obj instanceof SharedUserSetting) {
4078                final SharedUserSetting sus = (SharedUserSetting) obj;
4079                return sus.name + ":" + sus.userId;
4080            } else if (obj instanceof PackageSetting) {
4081                final PackageSetting ps = (PackageSetting) obj;
4082                return ps.name;
4083            }
4084        }
4085        return null;
4086    }
4087
4088    @Override
4089    public int getUidForSharedUser(String sharedUserName) {
4090        if(sharedUserName == null) {
4091            return -1;
4092        }
4093        // reader
4094        synchronized (mPackages) {
4095            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4096            if (suid == null) {
4097                return -1;
4098            }
4099            return suid.userId;
4100        }
4101    }
4102
4103    @Override
4104    public int getFlagsForUid(int uid) {
4105        synchronized (mPackages) {
4106            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4107            if (obj instanceof SharedUserSetting) {
4108                final SharedUserSetting sus = (SharedUserSetting) obj;
4109                return sus.pkgFlags;
4110            } else if (obj instanceof PackageSetting) {
4111                final PackageSetting ps = (PackageSetting) obj;
4112                return ps.pkgFlags;
4113            }
4114        }
4115        return 0;
4116    }
4117
4118    @Override
4119    public int getPrivateFlagsForUid(int uid) {
4120        synchronized (mPackages) {
4121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4122            if (obj instanceof SharedUserSetting) {
4123                final SharedUserSetting sus = (SharedUserSetting) obj;
4124                return sus.pkgPrivateFlags;
4125            } else if (obj instanceof PackageSetting) {
4126                final PackageSetting ps = (PackageSetting) obj;
4127                return ps.pkgPrivateFlags;
4128            }
4129        }
4130        return 0;
4131    }
4132
4133    @Override
4134    public boolean isUidPrivileged(int uid) {
4135        uid = UserHandle.getAppId(uid);
4136        // reader
4137        synchronized (mPackages) {
4138            Object obj = mSettings.getUserIdLPr(uid);
4139            if (obj instanceof SharedUserSetting) {
4140                final SharedUserSetting sus = (SharedUserSetting) obj;
4141                final Iterator<PackageSetting> it = sus.packages.iterator();
4142                while (it.hasNext()) {
4143                    if (it.next().isPrivileged()) {
4144                        return true;
4145                    }
4146                }
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.isPrivileged();
4150            }
4151        }
4152        return false;
4153    }
4154
4155    @Override
4156    public String[] getAppOpPermissionPackages(String permissionName) {
4157        synchronized (mPackages) {
4158            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4159            if (pkgs == null) {
4160                return null;
4161            }
4162            return pkgs.toArray(new String[pkgs.size()]);
4163        }
4164    }
4165
4166    @Override
4167    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4168            int flags, int userId) {
4169        if (!sUserManager.exists(userId)) return null;
4170        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4171        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4172        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4173    }
4174
4175    @Override
4176    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4177            IntentFilter filter, int match, ComponentName activity) {
4178        final int userId = UserHandle.getCallingUserId();
4179        if (DEBUG_PREFERRED) {
4180            Log.v(TAG, "setLastChosenActivity intent=" + intent
4181                + " resolvedType=" + resolvedType
4182                + " flags=" + flags
4183                + " filter=" + filter
4184                + " match=" + match
4185                + " activity=" + activity);
4186            filter.dump(new PrintStreamPrinter(System.out), "    ");
4187        }
4188        intent.setComponent(null);
4189        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4190        // Find any earlier preferred or last chosen entries and nuke them
4191        findPreferredActivity(intent, resolvedType,
4192                flags, query, 0, false, true, false, userId);
4193        // Add the new activity as the last chosen for this filter
4194        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4195                "Setting last chosen");
4196    }
4197
4198    @Override
4199    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4200        final int userId = UserHandle.getCallingUserId();
4201        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4202        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4203        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4204                false, false, false, userId);
4205    }
4206
4207    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4208            int flags, List<ResolveInfo> query, int userId) {
4209        if (query != null) {
4210            final int N = query.size();
4211            if (N == 1) {
4212                return query.get(0);
4213            } else if (N > 1) {
4214                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4215                // If there is more than one activity with the same priority,
4216                // then let the user decide between them.
4217                ResolveInfo r0 = query.get(0);
4218                ResolveInfo r1 = query.get(1);
4219                if (DEBUG_INTENT_MATCHING || debug) {
4220                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4221                            + r1.activityInfo.name + "=" + r1.priority);
4222                }
4223                // If the first activity has a higher priority, or a different
4224                // default, then it is always desireable to pick it.
4225                if (r0.priority != r1.priority
4226                        || r0.preferredOrder != r1.preferredOrder
4227                        || r0.isDefault != r1.isDefault) {
4228                    return query.get(0);
4229                }
4230                // If we have saved a preference for a preferred activity for
4231                // this Intent, use that.
4232                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4233                        flags, query, r0.priority, true, false, debug, userId);
4234                if (ri != null) {
4235                    return ri;
4236                }
4237                ri = new ResolveInfo(mResolveInfo);
4238                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4239                ri.activityInfo.applicationInfo = new ApplicationInfo(
4240                        ri.activityInfo.applicationInfo);
4241                if (userId != 0) {
4242                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4243                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4244                }
4245                // Make sure that the resolver is displayable in car mode
4246                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4247                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4248                return ri;
4249            }
4250        }
4251        return null;
4252    }
4253
4254    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4255            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4256        final int N = query.size();
4257        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4258                .get(userId);
4259        // Get the list of persistent preferred activities that handle the intent
4260        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4261        List<PersistentPreferredActivity> pprefs = ppir != null
4262                ? ppir.queryIntent(intent, resolvedType,
4263                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4264                : null;
4265        if (pprefs != null && pprefs.size() > 0) {
4266            final int M = pprefs.size();
4267            for (int i=0; i<M; i++) {
4268                final PersistentPreferredActivity ppa = pprefs.get(i);
4269                if (DEBUG_PREFERRED || debug) {
4270                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4271                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4272                            + "\n  component=" + ppa.mComponent);
4273                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4274                }
4275                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4276                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4277                if (DEBUG_PREFERRED || debug) {
4278                    Slog.v(TAG, "Found persistent preferred activity:");
4279                    if (ai != null) {
4280                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4281                    } else {
4282                        Slog.v(TAG, "  null");
4283                    }
4284                }
4285                if (ai == null) {
4286                    // This previously registered persistent preferred activity
4287                    // component is no longer known. Ignore it and do NOT remove it.
4288                    continue;
4289                }
4290                for (int j=0; j<N; j++) {
4291                    final ResolveInfo ri = query.get(j);
4292                    if (!ri.activityInfo.applicationInfo.packageName
4293                            .equals(ai.applicationInfo.packageName)) {
4294                        continue;
4295                    }
4296                    if (!ri.activityInfo.name.equals(ai.name)) {
4297                        continue;
4298                    }
4299                    //  Found a persistent preference that can handle the intent.
4300                    if (DEBUG_PREFERRED || debug) {
4301                        Slog.v(TAG, "Returning persistent preferred activity: " +
4302                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4303                    }
4304                    return ri;
4305                }
4306            }
4307        }
4308        return null;
4309    }
4310
4311    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4312            List<ResolveInfo> query, int priority, boolean always,
4313            boolean removeMatches, boolean debug, int userId) {
4314        if (!sUserManager.exists(userId)) return null;
4315        // writer
4316        synchronized (mPackages) {
4317            if (intent.getSelector() != null) {
4318                intent = intent.getSelector();
4319            }
4320            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4321
4322            // Try to find a matching persistent preferred activity.
4323            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4324                    debug, userId);
4325
4326            // If a persistent preferred activity matched, use it.
4327            if (pri != null) {
4328                return pri;
4329            }
4330
4331            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4332            // Get the list of preferred activities that handle the intent
4333            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4334            List<PreferredActivity> prefs = pir != null
4335                    ? pir.queryIntent(intent, resolvedType,
4336                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4337                    : null;
4338            if (prefs != null && prefs.size() > 0) {
4339                boolean changed = false;
4340                try {
4341                    // First figure out how good the original match set is.
4342                    // We will only allow preferred activities that came
4343                    // from the same match quality.
4344                    int match = 0;
4345
4346                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4347
4348                    final int N = query.size();
4349                    for (int j=0; j<N; j++) {
4350                        final ResolveInfo ri = query.get(j);
4351                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4352                                + ": 0x" + Integer.toHexString(match));
4353                        if (ri.match > match) {
4354                            match = ri.match;
4355                        }
4356                    }
4357
4358                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4359                            + Integer.toHexString(match));
4360
4361                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4362                    final int M = prefs.size();
4363                    for (int i=0; i<M; i++) {
4364                        final PreferredActivity pa = prefs.get(i);
4365                        if (DEBUG_PREFERRED || debug) {
4366                            Slog.v(TAG, "Checking PreferredActivity ds="
4367                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4368                                    + "\n  component=" + pa.mPref.mComponent);
4369                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4370                        }
4371                        if (pa.mPref.mMatch != match) {
4372                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4373                                    + Integer.toHexString(pa.mPref.mMatch));
4374                            continue;
4375                        }
4376                        // If it's not an "always" type preferred activity and that's what we're
4377                        // looking for, skip it.
4378                        if (always && !pa.mPref.mAlways) {
4379                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4380                            continue;
4381                        }
4382                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4383                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4384                        if (DEBUG_PREFERRED || debug) {
4385                            Slog.v(TAG, "Found preferred activity:");
4386                            if (ai != null) {
4387                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4388                            } else {
4389                                Slog.v(TAG, "  null");
4390                            }
4391                        }
4392                        if (ai == null) {
4393                            // This previously registered preferred activity
4394                            // component is no longer known.  Most likely an update
4395                            // to the app was installed and in the new version this
4396                            // component no longer exists.  Clean it up by removing
4397                            // it from the preferred activities list, and skip it.
4398                            Slog.w(TAG, "Removing dangling preferred activity: "
4399                                    + pa.mPref.mComponent);
4400                            pir.removeFilter(pa);
4401                            changed = true;
4402                            continue;
4403                        }
4404                        for (int j=0; j<N; j++) {
4405                            final ResolveInfo ri = query.get(j);
4406                            if (!ri.activityInfo.applicationInfo.packageName
4407                                    .equals(ai.applicationInfo.packageName)) {
4408                                continue;
4409                            }
4410                            if (!ri.activityInfo.name.equals(ai.name)) {
4411                                continue;
4412                            }
4413
4414                            if (removeMatches) {
4415                                pir.removeFilter(pa);
4416                                changed = true;
4417                                if (DEBUG_PREFERRED) {
4418                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4419                                }
4420                                break;
4421                            }
4422
4423                            // Okay we found a previously set preferred or last chosen app.
4424                            // If the result set is different from when this
4425                            // was created, we need to clear it and re-ask the
4426                            // user their preference, if we're looking for an "always" type entry.
4427                            if (always && !pa.mPref.sameSet(query)) {
4428                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4429                                        + intent + " type " + resolvedType);
4430                                if (DEBUG_PREFERRED) {
4431                                    Slog.v(TAG, "Removing preferred activity since set changed "
4432                                            + pa.mPref.mComponent);
4433                                }
4434                                pir.removeFilter(pa);
4435                                // Re-add the filter as a "last chosen" entry (!always)
4436                                PreferredActivity lastChosen = new PreferredActivity(
4437                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4438                                pir.addFilter(lastChosen);
4439                                changed = true;
4440                                return null;
4441                            }
4442
4443                            // Yay! Either the set matched or we're looking for the last chosen
4444                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4445                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4446                            return ri;
4447                        }
4448                    }
4449                } finally {
4450                    if (changed) {
4451                        if (DEBUG_PREFERRED) {
4452                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4453                        }
4454                        scheduleWritePackageRestrictionsLocked(userId);
4455                    }
4456                }
4457            }
4458        }
4459        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4460        return null;
4461    }
4462
4463    /*
4464     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4465     */
4466    @Override
4467    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4468            int targetUserId) {
4469        mContext.enforceCallingOrSelfPermission(
4470                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4471        List<CrossProfileIntentFilter> matches =
4472                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4473        if (matches != null) {
4474            int size = matches.size();
4475            for (int i = 0; i < size; i++) {
4476                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4477            }
4478        }
4479        if (hasWebURI(intent)) {
4480            // cross-profile app linking works only towards the parent.
4481            final UserInfo parent = getProfileParent(sourceUserId);
4482            synchronized(mPackages) {
4483                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4484                        intent, resolvedType, 0, sourceUserId, parent.id);
4485                return xpDomainInfo != null;
4486            }
4487        }
4488        return false;
4489    }
4490
4491    private UserInfo getProfileParent(int userId) {
4492        final long identity = Binder.clearCallingIdentity();
4493        try {
4494            return sUserManager.getProfileParent(userId);
4495        } finally {
4496            Binder.restoreCallingIdentity(identity);
4497        }
4498    }
4499
4500    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4501            String resolvedType, int userId) {
4502        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4503        if (resolver != null) {
4504            return resolver.queryIntent(intent, resolvedType, false, userId);
4505        }
4506        return null;
4507    }
4508
4509    @Override
4510    public List<ResolveInfo> queryIntentActivities(Intent intent,
4511            String resolvedType, int flags, int userId) {
4512        if (!sUserManager.exists(userId)) return Collections.emptyList();
4513        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4514        ComponentName comp = intent.getComponent();
4515        if (comp == null) {
4516            if (intent.getSelector() != null) {
4517                intent = intent.getSelector();
4518                comp = intent.getComponent();
4519            }
4520        }
4521
4522        if (comp != null) {
4523            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4524            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4525            if (ai != null) {
4526                final ResolveInfo ri = new ResolveInfo();
4527                ri.activityInfo = ai;
4528                list.add(ri);
4529            }
4530            return list;
4531        }
4532
4533        // reader
4534        synchronized (mPackages) {
4535            final String pkgName = intent.getPackage();
4536            if (pkgName == null) {
4537                List<CrossProfileIntentFilter> matchingFilters =
4538                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4539                // Check for results that need to skip the current profile.
4540                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4541                        resolvedType, flags, userId);
4542                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4543                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4544                    result.add(xpResolveInfo);
4545                    return filterIfNotPrimaryUser(result, userId);
4546                }
4547
4548                // Check for results in the current profile.
4549                List<ResolveInfo> result = mActivities.queryIntent(
4550                        intent, resolvedType, flags, userId);
4551
4552                // Check for cross profile results.
4553                xpResolveInfo = queryCrossProfileIntents(
4554                        matchingFilters, intent, resolvedType, flags, userId);
4555                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4556                    result.add(xpResolveInfo);
4557                    Collections.sort(result, mResolvePrioritySorter);
4558                }
4559                result = filterIfNotPrimaryUser(result, userId);
4560                if (hasWebURI(intent)) {
4561                    CrossProfileDomainInfo xpDomainInfo = null;
4562                    final UserInfo parent = getProfileParent(userId);
4563                    if (parent != null) {
4564                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4565                                flags, userId, parent.id);
4566                    }
4567                    if (xpDomainInfo != null) {
4568                        if (xpResolveInfo != null) {
4569                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4570                            // in the result.
4571                            result.remove(xpResolveInfo);
4572                        }
4573                        if (result.size() == 0) {
4574                            result.add(xpDomainInfo.resolveInfo);
4575                            return result;
4576                        }
4577                    } else if (result.size() <= 1) {
4578                        return result;
4579                    }
4580                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4581                            xpDomainInfo, userId);
4582                    Collections.sort(result, mResolvePrioritySorter);
4583                }
4584                return result;
4585            }
4586            final PackageParser.Package pkg = mPackages.get(pkgName);
4587            if (pkg != null) {
4588                return filterIfNotPrimaryUser(
4589                        mActivities.queryIntentForPackage(
4590                                intent, resolvedType, flags, pkg.activities, userId),
4591                        userId);
4592            }
4593            return new ArrayList<ResolveInfo>();
4594        }
4595    }
4596
4597    private static class CrossProfileDomainInfo {
4598        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4599        ResolveInfo resolveInfo;
4600        /* Best domain verification status of the activities found in the other profile */
4601        int bestDomainVerificationStatus;
4602    }
4603
4604    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4605            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4606        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4607                sourceUserId)) {
4608            return null;
4609        }
4610        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4611                resolvedType, flags, parentUserId);
4612
4613        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4614            return null;
4615        }
4616        CrossProfileDomainInfo result = null;
4617        int size = resultTargetUser.size();
4618        for (int i = 0; i < size; i++) {
4619            ResolveInfo riTargetUser = resultTargetUser.get(i);
4620            // Intent filter verification is only for filters that specify a host. So don't return
4621            // those that handle all web uris.
4622            if (riTargetUser.handleAllWebDataURI) {
4623                continue;
4624            }
4625            String packageName = riTargetUser.activityInfo.packageName;
4626            PackageSetting ps = mSettings.mPackages.get(packageName);
4627            if (ps == null) {
4628                continue;
4629            }
4630            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4631            int status = (int)(verificationState >> 32);
4632            if (result == null) {
4633                result = new CrossProfileDomainInfo();
4634                result.resolveInfo =
4635                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4636                result.bestDomainVerificationStatus = status;
4637            } else {
4638                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4639                        result.bestDomainVerificationStatus);
4640            }
4641        }
4642        // Don't consider matches with status NEVER across profiles.
4643        if (result != null && result.bestDomainVerificationStatus
4644                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4645            return null;
4646        }
4647        return result;
4648    }
4649
4650    /**
4651     * Verification statuses are ordered from the worse to the best, except for
4652     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4653     */
4654    private int bestDomainVerificationStatus(int status1, int status2) {
4655        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4656            return status2;
4657        }
4658        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4659            return status1;
4660        }
4661        return (int) MathUtils.max(status1, status2);
4662    }
4663
4664    private boolean isUserEnabled(int userId) {
4665        long callingId = Binder.clearCallingIdentity();
4666        try {
4667            UserInfo userInfo = sUserManager.getUserInfo(userId);
4668            return userInfo != null && userInfo.isEnabled();
4669        } finally {
4670            Binder.restoreCallingIdentity(callingId);
4671        }
4672    }
4673
4674    /**
4675     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4676     *
4677     * @return filtered list
4678     */
4679    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4680        if (userId == UserHandle.USER_OWNER) {
4681            return resolveInfos;
4682        }
4683        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4684            ResolveInfo info = resolveInfos.get(i);
4685            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4686                resolveInfos.remove(i);
4687            }
4688        }
4689        return resolveInfos;
4690    }
4691
4692    private static boolean hasWebURI(Intent intent) {
4693        if (intent.getData() == null) {
4694            return false;
4695        }
4696        final String scheme = intent.getScheme();
4697        if (TextUtils.isEmpty(scheme)) {
4698            return false;
4699        }
4700        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4701    }
4702
4703    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4704            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4705            int userId) {
4706        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4707
4708        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4709            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4710                    candidates.size());
4711        }
4712
4713        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4714        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4715        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4716        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4717        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4719
4720        synchronized (mPackages) {
4721            final int count = candidates.size();
4722            // First, try to use linked apps. Partition the candidates into four lists:
4723            // one for the final results, one for the "do not use ever", one for "undefined status"
4724            // and finally one for "browser app type".
4725            for (int n=0; n<count; n++) {
4726                ResolveInfo info = candidates.get(n);
4727                String packageName = info.activityInfo.packageName;
4728                PackageSetting ps = mSettings.mPackages.get(packageName);
4729                if (ps != null) {
4730                    // Add to the special match all list (Browser use case)
4731                    if (info.handleAllWebDataURI) {
4732                        matchAllList.add(info);
4733                        continue;
4734                    }
4735                    // Try to get the status from User settings first
4736                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4737                    int status = (int)(packedStatus >> 32);
4738                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4739                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4740                        if (DEBUG_DOMAIN_VERIFICATION) {
4741                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4742                                    + " : linkgen=" + linkGeneration);
4743                        }
4744                        // Use link-enabled generation as preferredOrder, i.e.
4745                        // prefer newly-enabled over earlier-enabled.
4746                        info.preferredOrder = linkGeneration;
4747                        alwaysList.add(info);
4748                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4749                        if (DEBUG_DOMAIN_VERIFICATION) {
4750                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4751                        }
4752                        neverList.add(info);
4753                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4754                        if (DEBUG_DOMAIN_VERIFICATION) {
4755                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4756                        }
4757                        alwaysAskList.add(info);
4758                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4759                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4760                        if (DEBUG_DOMAIN_VERIFICATION) {
4761                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4762                        }
4763                        undefinedList.add(info);
4764                    }
4765                }
4766            }
4767
4768            // We'll want to include browser possibilities in a few cases
4769            boolean includeBrowser = false;
4770
4771            // First try to add the "always" resolution(s) for the current user, if any
4772            if (alwaysList.size() > 0) {
4773                result.addAll(alwaysList);
4774            // if there is an "always" for the parent user, add it.
4775            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4776                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4777                result.add(xpDomainInfo.resolveInfo);
4778            } else {
4779                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4780                result.addAll(undefinedList);
4781                if (xpDomainInfo != null && (
4782                        xpDomainInfo.bestDomainVerificationStatus
4783                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4784                        || xpDomainInfo.bestDomainVerificationStatus
4785                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4786                    result.add(xpDomainInfo.resolveInfo);
4787                }
4788                includeBrowser = true;
4789            }
4790
4791            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4792            // If there were 'always' entries their preferred order has been set, so we also
4793            // back that off to make the alternatives equivalent
4794            if (alwaysAskList.size() > 0) {
4795                for (ResolveInfo i : result) {
4796                    i.preferredOrder = 0;
4797                }
4798                result.addAll(alwaysAskList);
4799                includeBrowser = true;
4800            }
4801
4802            if (includeBrowser) {
4803                // Also add browsers (all of them or only the default one)
4804                if (DEBUG_DOMAIN_VERIFICATION) {
4805                    Slog.v(TAG, "   ...including browsers in candidate set");
4806                }
4807                if ((matchFlags & MATCH_ALL) != 0) {
4808                    result.addAll(matchAllList);
4809                } else {
4810                    // Browser/generic handling case.  If there's a default browser, go straight
4811                    // to that (but only if there is no other higher-priority match).
4812                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4813                    int maxMatchPrio = 0;
4814                    ResolveInfo defaultBrowserMatch = null;
4815                    final int numCandidates = matchAllList.size();
4816                    for (int n = 0; n < numCandidates; n++) {
4817                        ResolveInfo info = matchAllList.get(n);
4818                        // track the highest overall match priority...
4819                        if (info.priority > maxMatchPrio) {
4820                            maxMatchPrio = info.priority;
4821                        }
4822                        // ...and the highest-priority default browser match
4823                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4824                            if (defaultBrowserMatch == null
4825                                    || (defaultBrowserMatch.priority < info.priority)) {
4826                                if (debug) {
4827                                    Slog.v(TAG, "Considering default browser match " + info);
4828                                }
4829                                defaultBrowserMatch = info;
4830                            }
4831                        }
4832                    }
4833                    if (defaultBrowserMatch != null
4834                            && defaultBrowserMatch.priority >= maxMatchPrio
4835                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4836                    {
4837                        if (debug) {
4838                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4839                        }
4840                        result.add(defaultBrowserMatch);
4841                    } else {
4842                        result.addAll(matchAllList);
4843                    }
4844                }
4845
4846                // If there is nothing selected, add all candidates and remove the ones that the user
4847                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4848                if (result.size() == 0) {
4849                    result.addAll(candidates);
4850                    result.removeAll(neverList);
4851                }
4852            }
4853        }
4854        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4855            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4856                    result.size());
4857            for (ResolveInfo info : result) {
4858                Slog.v(TAG, "  + " + info.activityInfo);
4859            }
4860        }
4861        return result;
4862    }
4863
4864    // Returns a packed value as a long:
4865    //
4866    // high 'int'-sized word: link status: undefined/ask/never/always.
4867    // low 'int'-sized word: relative priority among 'always' results.
4868    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4869        long result = ps.getDomainVerificationStatusForUser(userId);
4870        // if none available, get the master status
4871        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4872            if (ps.getIntentFilterVerificationInfo() != null) {
4873                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4874            }
4875        }
4876        return result;
4877    }
4878
4879    private ResolveInfo querySkipCurrentProfileIntents(
4880            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4881            int flags, int sourceUserId) {
4882        if (matchingFilters != null) {
4883            int size = matchingFilters.size();
4884            for (int i = 0; i < size; i ++) {
4885                CrossProfileIntentFilter filter = matchingFilters.get(i);
4886                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4887                    // Checking if there are activities in the target user that can handle the
4888                    // intent.
4889                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4890                            flags, sourceUserId);
4891                    if (resolveInfo != null) {
4892                        return resolveInfo;
4893                    }
4894                }
4895            }
4896        }
4897        return null;
4898    }
4899
4900    // Return matching ResolveInfo if any for skip current profile intent filters.
4901    private ResolveInfo queryCrossProfileIntents(
4902            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4903            int flags, int sourceUserId) {
4904        if (matchingFilters != null) {
4905            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4906            // match the same intent. For performance reasons, it is better not to
4907            // run queryIntent twice for the same userId
4908            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4909            int size = matchingFilters.size();
4910            for (int i = 0; i < size; i++) {
4911                CrossProfileIntentFilter filter = matchingFilters.get(i);
4912                int targetUserId = filter.getTargetUserId();
4913                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4914                        && !alreadyTriedUserIds.get(targetUserId)) {
4915                    // Checking if there are activities in the target user that can handle the
4916                    // intent.
4917                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4918                            flags, sourceUserId);
4919                    if (resolveInfo != null) return resolveInfo;
4920                    alreadyTriedUserIds.put(targetUserId, true);
4921                }
4922            }
4923        }
4924        return null;
4925    }
4926
4927    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4928            String resolvedType, int flags, int sourceUserId) {
4929        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4930                resolvedType, flags, filter.getTargetUserId());
4931        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4932            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4933        }
4934        return null;
4935    }
4936
4937    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4938            int sourceUserId, int targetUserId) {
4939        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4940        String className;
4941        if (targetUserId == UserHandle.USER_OWNER) {
4942            className = FORWARD_INTENT_TO_USER_OWNER;
4943        } else {
4944            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4945        }
4946        ComponentName forwardingActivityComponentName = new ComponentName(
4947                mAndroidApplication.packageName, className);
4948        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4949                sourceUserId);
4950        if (targetUserId == UserHandle.USER_OWNER) {
4951            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4952            forwardingResolveInfo.noResourceId = true;
4953        }
4954        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4955        forwardingResolveInfo.priority = 0;
4956        forwardingResolveInfo.preferredOrder = 0;
4957        forwardingResolveInfo.match = 0;
4958        forwardingResolveInfo.isDefault = true;
4959        forwardingResolveInfo.filter = filter;
4960        forwardingResolveInfo.targetUserId = targetUserId;
4961        return forwardingResolveInfo;
4962    }
4963
4964    @Override
4965    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4966            Intent[] specifics, String[] specificTypes, Intent intent,
4967            String resolvedType, int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return Collections.emptyList();
4969        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4970                false, "query intent activity options");
4971        final String resultsAction = intent.getAction();
4972
4973        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4974                | PackageManager.GET_RESOLVED_FILTER, userId);
4975
4976        if (DEBUG_INTENT_MATCHING) {
4977            Log.v(TAG, "Query " + intent + ": " + results);
4978        }
4979
4980        int specificsPos = 0;
4981        int N;
4982
4983        // todo: note that the algorithm used here is O(N^2).  This
4984        // isn't a problem in our current environment, but if we start running
4985        // into situations where we have more than 5 or 10 matches then this
4986        // should probably be changed to something smarter...
4987
4988        // First we go through and resolve each of the specific items
4989        // that were supplied, taking care of removing any corresponding
4990        // duplicate items in the generic resolve list.
4991        if (specifics != null) {
4992            for (int i=0; i<specifics.length; i++) {
4993                final Intent sintent = specifics[i];
4994                if (sintent == null) {
4995                    continue;
4996                }
4997
4998                if (DEBUG_INTENT_MATCHING) {
4999                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5000                }
5001
5002                String action = sintent.getAction();
5003                if (resultsAction != null && resultsAction.equals(action)) {
5004                    // If this action was explicitly requested, then don't
5005                    // remove things that have it.
5006                    action = null;
5007                }
5008
5009                ResolveInfo ri = null;
5010                ActivityInfo ai = null;
5011
5012                ComponentName comp = sintent.getComponent();
5013                if (comp == null) {
5014                    ri = resolveIntent(
5015                        sintent,
5016                        specificTypes != null ? specificTypes[i] : null,
5017                            flags, userId);
5018                    if (ri == null) {
5019                        continue;
5020                    }
5021                    if (ri == mResolveInfo) {
5022                        // ACK!  Must do something better with this.
5023                    }
5024                    ai = ri.activityInfo;
5025                    comp = new ComponentName(ai.applicationInfo.packageName,
5026                            ai.name);
5027                } else {
5028                    ai = getActivityInfo(comp, flags, userId);
5029                    if (ai == null) {
5030                        continue;
5031                    }
5032                }
5033
5034                // Look for any generic query activities that are duplicates
5035                // of this specific one, and remove them from the results.
5036                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5037                N = results.size();
5038                int j;
5039                for (j=specificsPos; j<N; j++) {
5040                    ResolveInfo sri = results.get(j);
5041                    if ((sri.activityInfo.name.equals(comp.getClassName())
5042                            && sri.activityInfo.applicationInfo.packageName.equals(
5043                                    comp.getPackageName()))
5044                        || (action != null && sri.filter.matchAction(action))) {
5045                        results.remove(j);
5046                        if (DEBUG_INTENT_MATCHING) Log.v(
5047                            TAG, "Removing duplicate item from " + j
5048                            + " due to specific " + specificsPos);
5049                        if (ri == null) {
5050                            ri = sri;
5051                        }
5052                        j--;
5053                        N--;
5054                    }
5055                }
5056
5057                // Add this specific item to its proper place.
5058                if (ri == null) {
5059                    ri = new ResolveInfo();
5060                    ri.activityInfo = ai;
5061                }
5062                results.add(specificsPos, ri);
5063                ri.specificIndex = i;
5064                specificsPos++;
5065            }
5066        }
5067
5068        // Now we go through the remaining generic results and remove any
5069        // duplicate actions that are found here.
5070        N = results.size();
5071        for (int i=specificsPos; i<N-1; i++) {
5072            final ResolveInfo rii = results.get(i);
5073            if (rii.filter == null) {
5074                continue;
5075            }
5076
5077            // Iterate over all of the actions of this result's intent
5078            // filter...  typically this should be just one.
5079            final Iterator<String> it = rii.filter.actionsIterator();
5080            if (it == null) {
5081                continue;
5082            }
5083            while (it.hasNext()) {
5084                final String action = it.next();
5085                if (resultsAction != null && resultsAction.equals(action)) {
5086                    // If this action was explicitly requested, then don't
5087                    // remove things that have it.
5088                    continue;
5089                }
5090                for (int j=i+1; j<N; j++) {
5091                    final ResolveInfo rij = results.get(j);
5092                    if (rij.filter != null && rij.filter.hasAction(action)) {
5093                        results.remove(j);
5094                        if (DEBUG_INTENT_MATCHING) Log.v(
5095                            TAG, "Removing duplicate item from " + j
5096                            + " due to action " + action + " at " + i);
5097                        j--;
5098                        N--;
5099                    }
5100                }
5101            }
5102
5103            // If the caller didn't request filter information, drop it now
5104            // so we don't have to marshall/unmarshall it.
5105            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5106                rii.filter = null;
5107            }
5108        }
5109
5110        // Filter out the caller activity if so requested.
5111        if (caller != null) {
5112            N = results.size();
5113            for (int i=0; i<N; i++) {
5114                ActivityInfo ainfo = results.get(i).activityInfo;
5115                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5116                        && caller.getClassName().equals(ainfo.name)) {
5117                    results.remove(i);
5118                    break;
5119                }
5120            }
5121        }
5122
5123        // If the caller didn't request filter information,
5124        // drop them now so we don't have to
5125        // marshall/unmarshall it.
5126        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5127            N = results.size();
5128            for (int i=0; i<N; i++) {
5129                results.get(i).filter = null;
5130            }
5131        }
5132
5133        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5134        return results;
5135    }
5136
5137    @Override
5138    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5139            int userId) {
5140        if (!sUserManager.exists(userId)) return Collections.emptyList();
5141        ComponentName comp = intent.getComponent();
5142        if (comp == null) {
5143            if (intent.getSelector() != null) {
5144                intent = intent.getSelector();
5145                comp = intent.getComponent();
5146            }
5147        }
5148        if (comp != null) {
5149            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5150            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5151            if (ai != null) {
5152                ResolveInfo ri = new ResolveInfo();
5153                ri.activityInfo = ai;
5154                list.add(ri);
5155            }
5156            return list;
5157        }
5158
5159        // reader
5160        synchronized (mPackages) {
5161            String pkgName = intent.getPackage();
5162            if (pkgName == null) {
5163                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5164            }
5165            final PackageParser.Package pkg = mPackages.get(pkgName);
5166            if (pkg != null) {
5167                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5168                        userId);
5169            }
5170            return null;
5171        }
5172    }
5173
5174    @Override
5175    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5176        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5177        if (!sUserManager.exists(userId)) return null;
5178        if (query != null) {
5179            if (query.size() >= 1) {
5180                // If there is more than one service with the same priority,
5181                // just arbitrarily pick the first one.
5182                return query.get(0);
5183            }
5184        }
5185        return null;
5186    }
5187
5188    @Override
5189    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5190            int userId) {
5191        if (!sUserManager.exists(userId)) return Collections.emptyList();
5192        ComponentName comp = intent.getComponent();
5193        if (comp == null) {
5194            if (intent.getSelector() != null) {
5195                intent = intent.getSelector();
5196                comp = intent.getComponent();
5197            }
5198        }
5199        if (comp != null) {
5200            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5201            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5202            if (si != null) {
5203                final ResolveInfo ri = new ResolveInfo();
5204                ri.serviceInfo = si;
5205                list.add(ri);
5206            }
5207            return list;
5208        }
5209
5210        // reader
5211        synchronized (mPackages) {
5212            String pkgName = intent.getPackage();
5213            if (pkgName == null) {
5214                return mServices.queryIntent(intent, resolvedType, flags, userId);
5215            }
5216            final PackageParser.Package pkg = mPackages.get(pkgName);
5217            if (pkg != null) {
5218                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5219                        userId);
5220            }
5221            return null;
5222        }
5223    }
5224
5225    @Override
5226    public List<ResolveInfo> queryIntentContentProviders(
5227            Intent intent, String resolvedType, int flags, int userId) {
5228        if (!sUserManager.exists(userId)) return Collections.emptyList();
5229        ComponentName comp = intent.getComponent();
5230        if (comp == null) {
5231            if (intent.getSelector() != null) {
5232                intent = intent.getSelector();
5233                comp = intent.getComponent();
5234            }
5235        }
5236        if (comp != null) {
5237            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5238            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5239            if (pi != null) {
5240                final ResolveInfo ri = new ResolveInfo();
5241                ri.providerInfo = pi;
5242                list.add(ri);
5243            }
5244            return list;
5245        }
5246
5247        // reader
5248        synchronized (mPackages) {
5249            String pkgName = intent.getPackage();
5250            if (pkgName == null) {
5251                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5252            }
5253            final PackageParser.Package pkg = mPackages.get(pkgName);
5254            if (pkg != null) {
5255                return mProviders.queryIntentForPackage(
5256                        intent, resolvedType, flags, pkg.providers, userId);
5257            }
5258            return null;
5259        }
5260    }
5261
5262    @Override
5263    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5264        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5265
5266        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5267
5268        // writer
5269        synchronized (mPackages) {
5270            ArrayList<PackageInfo> list;
5271            if (listUninstalled) {
5272                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5273                for (PackageSetting ps : mSettings.mPackages.values()) {
5274                    PackageInfo pi;
5275                    if (ps.pkg != null) {
5276                        pi = generatePackageInfo(ps.pkg, flags, userId);
5277                    } else {
5278                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5279                    }
5280                    if (pi != null) {
5281                        list.add(pi);
5282                    }
5283                }
5284            } else {
5285                list = new ArrayList<PackageInfo>(mPackages.size());
5286                for (PackageParser.Package p : mPackages.values()) {
5287                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5288                    if (pi != null) {
5289                        list.add(pi);
5290                    }
5291                }
5292            }
5293
5294            return new ParceledListSlice<PackageInfo>(list);
5295        }
5296    }
5297
5298    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5299            String[] permissions, boolean[] tmp, int flags, int userId) {
5300        int numMatch = 0;
5301        final PermissionsState permissionsState = ps.getPermissionsState();
5302        for (int i=0; i<permissions.length; i++) {
5303            final String permission = permissions[i];
5304            if (permissionsState.hasPermission(permission, userId)) {
5305                tmp[i] = true;
5306                numMatch++;
5307            } else {
5308                tmp[i] = false;
5309            }
5310        }
5311        if (numMatch == 0) {
5312            return;
5313        }
5314        PackageInfo pi;
5315        if (ps.pkg != null) {
5316            pi = generatePackageInfo(ps.pkg, flags, userId);
5317        } else {
5318            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5319        }
5320        // The above might return null in cases of uninstalled apps or install-state
5321        // skew across users/profiles.
5322        if (pi != null) {
5323            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5324                if (numMatch == permissions.length) {
5325                    pi.requestedPermissions = permissions;
5326                } else {
5327                    pi.requestedPermissions = new String[numMatch];
5328                    numMatch = 0;
5329                    for (int i=0; i<permissions.length; i++) {
5330                        if (tmp[i]) {
5331                            pi.requestedPermissions[numMatch] = permissions[i];
5332                            numMatch++;
5333                        }
5334                    }
5335                }
5336            }
5337            list.add(pi);
5338        }
5339    }
5340
5341    @Override
5342    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5343            String[] permissions, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return null;
5345        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5346
5347        // writer
5348        synchronized (mPackages) {
5349            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5350            boolean[] tmpBools = new boolean[permissions.length];
5351            if (listUninstalled) {
5352                for (PackageSetting ps : mSettings.mPackages.values()) {
5353                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5354                }
5355            } else {
5356                for (PackageParser.Package pkg : mPackages.values()) {
5357                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5358                    if (ps != null) {
5359                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5360                                userId);
5361                    }
5362                }
5363            }
5364
5365            return new ParceledListSlice<PackageInfo>(list);
5366        }
5367    }
5368
5369    @Override
5370    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5371        if (!sUserManager.exists(userId)) return null;
5372        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5373
5374        // writer
5375        synchronized (mPackages) {
5376            ArrayList<ApplicationInfo> list;
5377            if (listUninstalled) {
5378                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5379                for (PackageSetting ps : mSettings.mPackages.values()) {
5380                    ApplicationInfo ai;
5381                    if (ps.pkg != null) {
5382                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5383                                ps.readUserState(userId), userId);
5384                    } else {
5385                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5386                    }
5387                    if (ai != null) {
5388                        list.add(ai);
5389                    }
5390                }
5391            } else {
5392                list = new ArrayList<ApplicationInfo>(mPackages.size());
5393                for (PackageParser.Package p : mPackages.values()) {
5394                    if (p.mExtras != null) {
5395                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5396                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5397                        if (ai != null) {
5398                            list.add(ai);
5399                        }
5400                    }
5401                }
5402            }
5403
5404            return new ParceledListSlice<ApplicationInfo>(list);
5405        }
5406    }
5407
5408    public List<ApplicationInfo> getPersistentApplications(int flags) {
5409        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5410
5411        // reader
5412        synchronized (mPackages) {
5413            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5414            final int userId = UserHandle.getCallingUserId();
5415            while (i.hasNext()) {
5416                final PackageParser.Package p = i.next();
5417                if (p.applicationInfo != null
5418                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5419                        && (!mSafeMode || isSystemApp(p))) {
5420                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5421                    if (ps != null) {
5422                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5423                                ps.readUserState(userId), userId);
5424                        if (ai != null) {
5425                            finalList.add(ai);
5426                        }
5427                    }
5428                }
5429            }
5430        }
5431
5432        return finalList;
5433    }
5434
5435    @Override
5436    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5437        if (!sUserManager.exists(userId)) return null;
5438        // reader
5439        synchronized (mPackages) {
5440            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5441            PackageSetting ps = provider != null
5442                    ? mSettings.mPackages.get(provider.owner.packageName)
5443                    : null;
5444            return ps != null
5445                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5446                    && (!mSafeMode || (provider.info.applicationInfo.flags
5447                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5448                    ? PackageParser.generateProviderInfo(provider, flags,
5449                            ps.readUserState(userId), userId)
5450                    : null;
5451        }
5452    }
5453
5454    /**
5455     * @deprecated
5456     */
5457    @Deprecated
5458    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5459        // reader
5460        synchronized (mPackages) {
5461            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5462                    .entrySet().iterator();
5463            final int userId = UserHandle.getCallingUserId();
5464            while (i.hasNext()) {
5465                Map.Entry<String, PackageParser.Provider> entry = i.next();
5466                PackageParser.Provider p = entry.getValue();
5467                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5468
5469                if (ps != null && p.syncable
5470                        && (!mSafeMode || (p.info.applicationInfo.flags
5471                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5472                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5473                            ps.readUserState(userId), userId);
5474                    if (info != null) {
5475                        outNames.add(entry.getKey());
5476                        outInfo.add(info);
5477                    }
5478                }
5479            }
5480        }
5481    }
5482
5483    @Override
5484    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5485            int uid, int flags) {
5486        ArrayList<ProviderInfo> finalList = null;
5487        // reader
5488        synchronized (mPackages) {
5489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5490            final int userId = processName != null ?
5491                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5492            while (i.hasNext()) {
5493                final PackageParser.Provider p = i.next();
5494                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5495                if (ps != null && p.info.authority != null
5496                        && (processName == null
5497                                || (p.info.processName.equals(processName)
5498                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5499                        && mSettings.isEnabledLPr(p.info, flags, userId)
5500                        && (!mSafeMode
5501                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5502                    if (finalList == null) {
5503                        finalList = new ArrayList<ProviderInfo>(3);
5504                    }
5505                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5506                            ps.readUserState(userId), userId);
5507                    if (info != null) {
5508                        finalList.add(info);
5509                    }
5510                }
5511            }
5512        }
5513
5514        if (finalList != null) {
5515            Collections.sort(finalList, mProviderInitOrderSorter);
5516            return new ParceledListSlice<ProviderInfo>(finalList);
5517        }
5518
5519        return null;
5520    }
5521
5522    @Override
5523    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5524            int flags) {
5525        // reader
5526        synchronized (mPackages) {
5527            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5528            return PackageParser.generateInstrumentationInfo(i, flags);
5529        }
5530    }
5531
5532    @Override
5533    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5534            int flags) {
5535        ArrayList<InstrumentationInfo> finalList =
5536            new ArrayList<InstrumentationInfo>();
5537
5538        // reader
5539        synchronized (mPackages) {
5540            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5541            while (i.hasNext()) {
5542                final PackageParser.Instrumentation p = i.next();
5543                if (targetPackage == null
5544                        || targetPackage.equals(p.info.targetPackage)) {
5545                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5546                            flags);
5547                    if (ii != null) {
5548                        finalList.add(ii);
5549                    }
5550                }
5551            }
5552        }
5553
5554        return finalList;
5555    }
5556
5557    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5558        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5559        if (overlays == null) {
5560            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5561            return;
5562        }
5563        for (PackageParser.Package opkg : overlays.values()) {
5564            // Not much to do if idmap fails: we already logged the error
5565            // and we certainly don't want to abort installation of pkg simply
5566            // because an overlay didn't fit properly. For these reasons,
5567            // ignore the return value of createIdmapForPackagePairLI.
5568            createIdmapForPackagePairLI(pkg, opkg);
5569        }
5570    }
5571
5572    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5573            PackageParser.Package opkg) {
5574        if (!opkg.mTrustedOverlay) {
5575            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5576                    opkg.baseCodePath + ": overlay not trusted");
5577            return false;
5578        }
5579        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5580        if (overlaySet == null) {
5581            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5582                    opkg.baseCodePath + " but target package has no known overlays");
5583            return false;
5584        }
5585        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5586        // TODO: generate idmap for split APKs
5587        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5588            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5589                    + opkg.baseCodePath);
5590            return false;
5591        }
5592        PackageParser.Package[] overlayArray =
5593            overlaySet.values().toArray(new PackageParser.Package[0]);
5594        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5595            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5596                return p1.mOverlayPriority - p2.mOverlayPriority;
5597            }
5598        };
5599        Arrays.sort(overlayArray, cmp);
5600
5601        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5602        int i = 0;
5603        for (PackageParser.Package p : overlayArray) {
5604            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5605        }
5606        return true;
5607    }
5608
5609    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5610        final File[] files = dir.listFiles();
5611        if (ArrayUtils.isEmpty(files)) {
5612            Log.d(TAG, "No files in app dir " + dir);
5613            return;
5614        }
5615
5616        if (DEBUG_PACKAGE_SCANNING) {
5617            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5618                    + " flags=0x" + Integer.toHexString(parseFlags));
5619        }
5620
5621        for (File file : files) {
5622            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5623                    && !PackageInstallerService.isStageName(file.getName());
5624            if (!isPackage) {
5625                // Ignore entries which are not packages
5626                continue;
5627            }
5628            try {
5629                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5630                        scanFlags, currentTime, null);
5631            } catch (PackageManagerException e) {
5632                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5633
5634                // Delete invalid userdata apps
5635                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5636                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5637                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5638                    if (file.isDirectory()) {
5639                        mInstaller.rmPackageDir(file.getAbsolutePath());
5640                    } else {
5641                        file.delete();
5642                    }
5643                }
5644            }
5645        }
5646    }
5647
5648    private static File getSettingsProblemFile() {
5649        File dataDir = Environment.getDataDirectory();
5650        File systemDir = new File(dataDir, "system");
5651        File fname = new File(systemDir, "uiderrors.txt");
5652        return fname;
5653    }
5654
5655    static void reportSettingsProblem(int priority, String msg) {
5656        logCriticalInfo(priority, msg);
5657    }
5658
5659    static void logCriticalInfo(int priority, String msg) {
5660        Slog.println(priority, TAG, msg);
5661        EventLogTags.writePmCriticalInfo(msg);
5662        try {
5663            File fname = getSettingsProblemFile();
5664            FileOutputStream out = new FileOutputStream(fname, true);
5665            PrintWriter pw = new FastPrintWriter(out);
5666            SimpleDateFormat formatter = new SimpleDateFormat();
5667            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5668            pw.println(dateString + ": " + msg);
5669            pw.close();
5670            FileUtils.setPermissions(
5671                    fname.toString(),
5672                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5673                    -1, -1);
5674        } catch (java.io.IOException e) {
5675        }
5676    }
5677
5678    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5679            PackageParser.Package pkg, File srcFile, int parseFlags)
5680            throws PackageManagerException {
5681        if (ps != null
5682                && ps.codePath.equals(srcFile)
5683                && ps.timeStamp == srcFile.lastModified()
5684                && !isCompatSignatureUpdateNeeded(pkg)
5685                && !isRecoverSignatureUpdateNeeded(pkg)) {
5686            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5687            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5688            ArraySet<PublicKey> signingKs;
5689            synchronized (mPackages) {
5690                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5691            }
5692            if (ps.signatures.mSignatures != null
5693                    && ps.signatures.mSignatures.length != 0
5694                    && signingKs != null) {
5695                // Optimization: reuse the existing cached certificates
5696                // if the package appears to be unchanged.
5697                pkg.mSignatures = ps.signatures.mSignatures;
5698                pkg.mSigningKeys = signingKs;
5699                return;
5700            }
5701
5702            Slog.w(TAG, "PackageSetting for " + ps.name
5703                    + " is missing signatures.  Collecting certs again to recover them.");
5704        } else {
5705            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5706        }
5707
5708        try {
5709            pp.collectCertificates(pkg, parseFlags);
5710            pp.collectManifestDigest(pkg);
5711        } catch (PackageParserException e) {
5712            throw PackageManagerException.from(e);
5713        }
5714    }
5715
5716    /*
5717     *  Scan a package and return the newly parsed package.
5718     *  Returns null in case of errors and the error code is stored in mLastScanError
5719     */
5720    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5721            long currentTime, UserHandle user) throws PackageManagerException {
5722        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5723        parseFlags |= mDefParseFlags;
5724        PackageParser pp = new PackageParser();
5725        pp.setSeparateProcesses(mSeparateProcesses);
5726        pp.setOnlyCoreApps(mOnlyCore);
5727        pp.setDisplayMetrics(mMetrics);
5728
5729        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5730            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5731        }
5732
5733        final PackageParser.Package pkg;
5734        try {
5735            pkg = pp.parsePackage(scanFile, parseFlags);
5736        } catch (PackageParserException e) {
5737            throw PackageManagerException.from(e);
5738        }
5739
5740        PackageSetting ps = null;
5741        PackageSetting updatedPkg;
5742        // reader
5743        synchronized (mPackages) {
5744            // Look to see if we already know about this package.
5745            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5746            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5747                // This package has been renamed to its original name.  Let's
5748                // use that.
5749                ps = mSettings.peekPackageLPr(oldName);
5750            }
5751            // If there was no original package, see one for the real package name.
5752            if (ps == null) {
5753                ps = mSettings.peekPackageLPr(pkg.packageName);
5754            }
5755            // Check to see if this package could be hiding/updating a system
5756            // package.  Must look for it either under the original or real
5757            // package name depending on our state.
5758            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5759            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5760        }
5761        boolean updatedPkgBetter = false;
5762        // First check if this is a system package that may involve an update
5763        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5764            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5765            // it needs to drop FLAG_PRIVILEGED.
5766            if (locationIsPrivileged(scanFile)) {
5767                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5768            } else {
5769                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5770            }
5771
5772            if (ps != null && !ps.codePath.equals(scanFile)) {
5773                // The path has changed from what was last scanned...  check the
5774                // version of the new path against what we have stored to determine
5775                // what to do.
5776                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5777                if (pkg.mVersionCode <= ps.versionCode) {
5778                    // The system package has been updated and the code path does not match
5779                    // Ignore entry. Skip it.
5780                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5781                            + " ignored: updated version " + ps.versionCode
5782                            + " better than this " + pkg.mVersionCode);
5783                    if (!updatedPkg.codePath.equals(scanFile)) {
5784                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5785                                + ps.name + " changing from " + updatedPkg.codePathString
5786                                + " to " + scanFile);
5787                        updatedPkg.codePath = scanFile;
5788                        updatedPkg.codePathString = scanFile.toString();
5789                        updatedPkg.resourcePath = scanFile;
5790                        updatedPkg.resourcePathString = scanFile.toString();
5791                    }
5792                    updatedPkg.pkg = pkg;
5793                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5794                            "Package " + ps.name + " at " + scanFile
5795                                    + " ignored: updated version " + ps.versionCode
5796                                    + " better than this " + pkg.mVersionCode);
5797                } else {
5798                    // The current app on the system partition is better than
5799                    // what we have updated to on the data partition; switch
5800                    // back to the system partition version.
5801                    // At this point, its safely assumed that package installation for
5802                    // apps in system partition will go through. If not there won't be a working
5803                    // version of the app
5804                    // writer
5805                    synchronized (mPackages) {
5806                        // Just remove the loaded entries from package lists.
5807                        mPackages.remove(ps.name);
5808                    }
5809
5810                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5811                            + " reverting from " + ps.codePathString
5812                            + ": new version " + pkg.mVersionCode
5813                            + " better than installed " + ps.versionCode);
5814
5815                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5816                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5817                    synchronized (mInstallLock) {
5818                        args.cleanUpResourcesLI();
5819                    }
5820                    synchronized (mPackages) {
5821                        mSettings.enableSystemPackageLPw(ps.name);
5822                    }
5823                    updatedPkgBetter = true;
5824                }
5825            }
5826        }
5827
5828        if (updatedPkg != null) {
5829            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5830            // initially
5831            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5832
5833            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5834            // flag set initially
5835            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5836                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5837            }
5838        }
5839
5840        // Verify certificates against what was last scanned
5841        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5842
5843        /*
5844         * A new system app appeared, but we already had a non-system one of the
5845         * same name installed earlier.
5846         */
5847        boolean shouldHideSystemApp = false;
5848        if (updatedPkg == null && ps != null
5849                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5850            /*
5851             * Check to make sure the signatures match first. If they don't,
5852             * wipe the installed application and its data.
5853             */
5854            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5855                    != PackageManager.SIGNATURE_MATCH) {
5856                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5857                        + " signatures don't match existing userdata copy; removing");
5858                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5859                ps = null;
5860            } else {
5861                /*
5862                 * If the newly-added system app is an older version than the
5863                 * already installed version, hide it. It will be scanned later
5864                 * and re-added like an update.
5865                 */
5866                if (pkg.mVersionCode <= ps.versionCode) {
5867                    shouldHideSystemApp = true;
5868                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5869                            + " but new version " + pkg.mVersionCode + " better than installed "
5870                            + ps.versionCode + "; hiding system");
5871                } else {
5872                    /*
5873                     * The newly found system app is a newer version that the
5874                     * one previously installed. Simply remove the
5875                     * already-installed application and replace it with our own
5876                     * while keeping the application data.
5877                     */
5878                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5879                            + " reverting from " + ps.codePathString + ": new version "
5880                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5881                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5882                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5883                    synchronized (mInstallLock) {
5884                        args.cleanUpResourcesLI();
5885                    }
5886                }
5887            }
5888        }
5889
5890        // The apk is forward locked (not public) if its code and resources
5891        // are kept in different files. (except for app in either system or
5892        // vendor path).
5893        // TODO grab this value from PackageSettings
5894        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5895            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5896                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5897            }
5898        }
5899
5900        // TODO: extend to support forward-locked splits
5901        String resourcePath = null;
5902        String baseResourcePath = null;
5903        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5904            if (ps != null && ps.resourcePathString != null) {
5905                resourcePath = ps.resourcePathString;
5906                baseResourcePath = ps.resourcePathString;
5907            } else {
5908                // Should not happen at all. Just log an error.
5909                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5910            }
5911        } else {
5912            resourcePath = pkg.codePath;
5913            baseResourcePath = pkg.baseCodePath;
5914        }
5915
5916        // Set application objects path explicitly.
5917        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5918        pkg.applicationInfo.setCodePath(pkg.codePath);
5919        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5920        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5921        pkg.applicationInfo.setResourcePath(resourcePath);
5922        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5923        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5924
5925        // Note that we invoke the following method only if we are about to unpack an application
5926        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5927                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5928
5929        /*
5930         * If the system app should be overridden by a previously installed
5931         * data, hide the system app now and let the /data/app scan pick it up
5932         * again.
5933         */
5934        if (shouldHideSystemApp) {
5935            synchronized (mPackages) {
5936                /*
5937                 * We have to grant systems permissions before we hide, because
5938                 * grantPermissions will assume the package update is trying to
5939                 * expand its permissions.
5940                 */
5941                grantPermissionsLPw(pkg, true, pkg.packageName);
5942                mSettings.disableSystemPackageLPw(pkg.packageName);
5943            }
5944        }
5945
5946        return scannedPkg;
5947    }
5948
5949    private static String fixProcessName(String defProcessName,
5950            String processName, int uid) {
5951        if (processName == null) {
5952            return defProcessName;
5953        }
5954        return processName;
5955    }
5956
5957    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5958            throws PackageManagerException {
5959        if (pkgSetting.signatures.mSignatures != null) {
5960            // Already existing package. Make sure signatures match
5961            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5962                    == PackageManager.SIGNATURE_MATCH;
5963            if (!match) {
5964                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5965                        == PackageManager.SIGNATURE_MATCH;
5966            }
5967            if (!match) {
5968                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5969                        == PackageManager.SIGNATURE_MATCH;
5970            }
5971            if (!match) {
5972                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5973                        + pkg.packageName + " signatures do not match the "
5974                        + "previously installed version; ignoring!");
5975            }
5976        }
5977
5978        // Check for shared user signatures
5979        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5980            // Already existing package. Make sure signatures match
5981            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5982                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5983            if (!match) {
5984                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5985                        == PackageManager.SIGNATURE_MATCH;
5986            }
5987            if (!match) {
5988                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5989                        == PackageManager.SIGNATURE_MATCH;
5990            }
5991            if (!match) {
5992                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5993                        "Package " + pkg.packageName
5994                        + " has no signatures that match those in shared user "
5995                        + pkgSetting.sharedUser.name + "; ignoring!");
5996            }
5997        }
5998    }
5999
6000    /**
6001     * Enforces that only the system UID or root's UID can call a method exposed
6002     * via Binder.
6003     *
6004     * @param message used as message if SecurityException is thrown
6005     * @throws SecurityException if the caller is not system or root
6006     */
6007    private static final void enforceSystemOrRoot(String message) {
6008        final int uid = Binder.getCallingUid();
6009        if (uid != Process.SYSTEM_UID && uid != 0) {
6010            throw new SecurityException(message);
6011        }
6012    }
6013
6014    @Override
6015    public void performBootDexOpt() {
6016        enforceSystemOrRoot("Only the system can request dexopt be performed");
6017
6018        // Before everything else, see whether we need to fstrim.
6019        try {
6020            IMountService ms = PackageHelper.getMountService();
6021            if (ms != null) {
6022                final boolean isUpgrade = isUpgrade();
6023                boolean doTrim = isUpgrade;
6024                if (doTrim) {
6025                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6026                } else {
6027                    final long interval = android.provider.Settings.Global.getLong(
6028                            mContext.getContentResolver(),
6029                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6030                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6031                    if (interval > 0) {
6032                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6033                        if (timeSinceLast > interval) {
6034                            doTrim = true;
6035                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6036                                    + "; running immediately");
6037                        }
6038                    }
6039                }
6040                if (doTrim) {
6041                    if (!isFirstBoot()) {
6042                        try {
6043                            ActivityManagerNative.getDefault().showBootMessage(
6044                                    mContext.getResources().getString(
6045                                            R.string.android_upgrading_fstrim), true);
6046                        } catch (RemoteException e) {
6047                        }
6048                    }
6049                    ms.runMaintenance();
6050                }
6051            } else {
6052                Slog.e(TAG, "Mount service unavailable!");
6053            }
6054        } catch (RemoteException e) {
6055            // Can't happen; MountService is local
6056        }
6057
6058        final ArraySet<PackageParser.Package> pkgs;
6059        synchronized (mPackages) {
6060            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6061        }
6062
6063        if (pkgs != null) {
6064            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6065            // in case the device runs out of space.
6066            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6067            // Give priority to core apps.
6068            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6069                PackageParser.Package pkg = it.next();
6070                if (pkg.coreApp) {
6071                    if (DEBUG_DEXOPT) {
6072                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6073                    }
6074                    sortedPkgs.add(pkg);
6075                    it.remove();
6076                }
6077            }
6078            // Give priority to system apps that listen for pre boot complete.
6079            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6080            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6081            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6082                PackageParser.Package pkg = it.next();
6083                if (pkgNames.contains(pkg.packageName)) {
6084                    if (DEBUG_DEXOPT) {
6085                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6086                    }
6087                    sortedPkgs.add(pkg);
6088                    it.remove();
6089                }
6090            }
6091            // Give priority to system apps.
6092            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6093                PackageParser.Package pkg = it.next();
6094                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6095                    if (DEBUG_DEXOPT) {
6096                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6097                    }
6098                    sortedPkgs.add(pkg);
6099                    it.remove();
6100                }
6101            }
6102            // Give priority to updated system apps.
6103            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6104                PackageParser.Package pkg = it.next();
6105                if (pkg.isUpdatedSystemApp()) {
6106                    if (DEBUG_DEXOPT) {
6107                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6108                    }
6109                    sortedPkgs.add(pkg);
6110                    it.remove();
6111                }
6112            }
6113            // Give priority to apps that listen for boot complete.
6114            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6115            pkgNames = getPackageNamesForIntent(intent);
6116            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6117                PackageParser.Package pkg = it.next();
6118                if (pkgNames.contains(pkg.packageName)) {
6119                    if (DEBUG_DEXOPT) {
6120                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6121                    }
6122                    sortedPkgs.add(pkg);
6123                    it.remove();
6124                }
6125            }
6126            // Filter out packages that aren't recently used.
6127            filterRecentlyUsedApps(pkgs);
6128            // Add all remaining apps.
6129            for (PackageParser.Package pkg : pkgs) {
6130                if (DEBUG_DEXOPT) {
6131                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6132                }
6133                sortedPkgs.add(pkg);
6134            }
6135
6136            // If we want to be lazy, filter everything that wasn't recently used.
6137            if (mLazyDexOpt) {
6138                filterRecentlyUsedApps(sortedPkgs);
6139            }
6140
6141            int i = 0;
6142            int total = sortedPkgs.size();
6143            File dataDir = Environment.getDataDirectory();
6144            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6145            if (lowThreshold == 0) {
6146                throw new IllegalStateException("Invalid low memory threshold");
6147            }
6148            for (PackageParser.Package pkg : sortedPkgs) {
6149                long usableSpace = dataDir.getUsableSpace();
6150                if (usableSpace < lowThreshold) {
6151                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6152                    break;
6153                }
6154                performBootDexOpt(pkg, ++i, total);
6155            }
6156        }
6157    }
6158
6159    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6160        // Filter out packages that aren't recently used.
6161        //
6162        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6163        // should do a full dexopt.
6164        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6165            int total = pkgs.size();
6166            int skipped = 0;
6167            long now = System.currentTimeMillis();
6168            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6169                PackageParser.Package pkg = i.next();
6170                long then = pkg.mLastPackageUsageTimeInMills;
6171                if (then + mDexOptLRUThresholdInMills < now) {
6172                    if (DEBUG_DEXOPT) {
6173                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6174                              ((then == 0) ? "never" : new Date(then)));
6175                    }
6176                    i.remove();
6177                    skipped++;
6178                }
6179            }
6180            if (DEBUG_DEXOPT) {
6181                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6182            }
6183        }
6184    }
6185
6186    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6187        List<ResolveInfo> ris = null;
6188        try {
6189            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6190                    intent, null, 0, UserHandle.USER_OWNER);
6191        } catch (RemoteException e) {
6192        }
6193        ArraySet<String> pkgNames = new ArraySet<String>();
6194        if (ris != null) {
6195            for (ResolveInfo ri : ris) {
6196                pkgNames.add(ri.activityInfo.packageName);
6197            }
6198        }
6199        return pkgNames;
6200    }
6201
6202    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6203        if (DEBUG_DEXOPT) {
6204            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6205        }
6206        if (!isFirstBoot()) {
6207            try {
6208                ActivityManagerNative.getDefault().showBootMessage(
6209                        mContext.getResources().getString(R.string.android_upgrading_apk,
6210                                curr, total), true);
6211            } catch (RemoteException e) {
6212            }
6213        }
6214        PackageParser.Package p = pkg;
6215        synchronized (mInstallLock) {
6216            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6217                    false /* force dex */, false /* defer */, true /* include dependencies */);
6218        }
6219    }
6220
6221    @Override
6222    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6223        return performDexOpt(packageName, instructionSet, false);
6224    }
6225
6226    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6227        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6228        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6229        if (!dexopt && !updateUsage) {
6230            // We aren't going to dexopt or update usage, so bail early.
6231            return false;
6232        }
6233        PackageParser.Package p;
6234        final String targetInstructionSet;
6235        synchronized (mPackages) {
6236            p = mPackages.get(packageName);
6237            if (p == null) {
6238                return false;
6239            }
6240            if (updateUsage) {
6241                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6242            }
6243            mPackageUsage.write(false);
6244            if (!dexopt) {
6245                // We aren't going to dexopt, so bail early.
6246                return false;
6247            }
6248
6249            targetInstructionSet = instructionSet != null ? instructionSet :
6250                    getPrimaryInstructionSet(p.applicationInfo);
6251            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6252                return false;
6253            }
6254        }
6255        long callingId = Binder.clearCallingIdentity();
6256        try {
6257            synchronized (mInstallLock) {
6258                final String[] instructionSets = new String[] { targetInstructionSet };
6259                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6260                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6261                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6262            }
6263        } finally {
6264            Binder.restoreCallingIdentity(callingId);
6265        }
6266    }
6267
6268    public ArraySet<String> getPackagesThatNeedDexOpt() {
6269        ArraySet<String> pkgs = null;
6270        synchronized (mPackages) {
6271            for (PackageParser.Package p : mPackages.values()) {
6272                if (DEBUG_DEXOPT) {
6273                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6274                }
6275                if (!p.mDexOptPerformed.isEmpty()) {
6276                    continue;
6277                }
6278                if (pkgs == null) {
6279                    pkgs = new ArraySet<String>();
6280                }
6281                pkgs.add(p.packageName);
6282            }
6283        }
6284        return pkgs;
6285    }
6286
6287    public void shutdown() {
6288        mPackageUsage.write(true);
6289    }
6290
6291    @Override
6292    public void forceDexOpt(String packageName) {
6293        enforceSystemOrRoot("forceDexOpt");
6294
6295        PackageParser.Package pkg;
6296        synchronized (mPackages) {
6297            pkg = mPackages.get(packageName);
6298            if (pkg == null) {
6299                throw new IllegalArgumentException("Missing package: " + packageName);
6300            }
6301        }
6302
6303        synchronized (mInstallLock) {
6304            final String[] instructionSets = new String[] {
6305                    getPrimaryInstructionSet(pkg.applicationInfo) };
6306            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6307                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
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);
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            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7106                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7107            }
7108        }
7109        if (mFactoryTest && pkg.requestedPermissions.contains(
7110                android.Manifest.permission.FACTORY_TEST)) {
7111            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7112        }
7113
7114        ArrayList<PackageParser.Package> clientLibPkgs = null;
7115
7116        // writer
7117        synchronized (mPackages) {
7118            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7119                // Only system apps can add new shared libraries.
7120                if (pkg.libraryNames != null) {
7121                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7122                        String name = pkg.libraryNames.get(i);
7123                        boolean allowed = false;
7124                        if (pkg.isUpdatedSystemApp()) {
7125                            // New library entries can only be added through the
7126                            // system image.  This is important to get rid of a lot
7127                            // of nasty edge cases: for example if we allowed a non-
7128                            // system update of the app to add a library, then uninstalling
7129                            // the update would make the library go away, and assumptions
7130                            // we made such as through app install filtering would now
7131                            // have allowed apps on the device which aren't compatible
7132                            // with it.  Better to just have the restriction here, be
7133                            // conservative, and create many fewer cases that can negatively
7134                            // impact the user experience.
7135                            final PackageSetting sysPs = mSettings
7136                                    .getDisabledSystemPkgLPr(pkg.packageName);
7137                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7138                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7139                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7140                                        allowed = true;
7141                                        allowed = true;
7142                                        break;
7143                                    }
7144                                }
7145                            }
7146                        } else {
7147                            allowed = true;
7148                        }
7149                        if (allowed) {
7150                            if (!mSharedLibraries.containsKey(name)) {
7151                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7152                            } else if (!name.equals(pkg.packageName)) {
7153                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7154                                        + name + " already exists; skipping");
7155                            }
7156                        } else {
7157                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7158                                    + name + " that is not declared on system image; skipping");
7159                        }
7160                    }
7161                    if ((scanFlags&SCAN_BOOTING) == 0) {
7162                        // If we are not booting, we need to update any applications
7163                        // that are clients of our shared library.  If we are booting,
7164                        // this will all be done once the scan is complete.
7165                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7166                    }
7167                }
7168            }
7169        }
7170
7171        // We also need to dexopt any apps that are dependent on this library.  Note that
7172        // if these fail, we should abort the install since installing the library will
7173        // result in some apps being broken.
7174        if (clientLibPkgs != null) {
7175            if ((scanFlags & SCAN_NO_DEX) == 0) {
7176                for (int i = 0; i < clientLibPkgs.size(); i++) {
7177                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7178                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7179                            null /* instruction sets */, forceDex,
7180                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7181                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7182                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7183                                "scanPackageLI failed to dexopt clientLibPkgs");
7184                    }
7185                }
7186            }
7187        }
7188
7189        // Request the ActivityManager to kill the process(only for existing packages)
7190        // so that we do not end up in a confused state while the user is still using the older
7191        // version of the application while the new one gets installed.
7192        if ((scanFlags & SCAN_REPLACING) != 0) {
7193            killApplication(pkg.applicationInfo.packageName,
7194                        pkg.applicationInfo.uid, "replace pkg");
7195        }
7196
7197        // Also need to kill any apps that are dependent on the library.
7198        if (clientLibPkgs != null) {
7199            for (int i=0; i<clientLibPkgs.size(); i++) {
7200                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7201                killApplication(clientPkg.applicationInfo.packageName,
7202                        clientPkg.applicationInfo.uid, "update lib");
7203            }
7204        }
7205
7206        // Make sure we're not adding any bogus keyset info
7207        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7208        ksms.assertScannedPackageValid(pkg);
7209
7210        // writer
7211        synchronized (mPackages) {
7212            // We don't expect installation to fail beyond this point
7213
7214            // Add the new setting to mSettings
7215            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7216            // Add the new setting to mPackages
7217            mPackages.put(pkg.applicationInfo.packageName, pkg);
7218            // Make sure we don't accidentally delete its data.
7219            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7220            while (iter.hasNext()) {
7221                PackageCleanItem item = iter.next();
7222                if (pkgName.equals(item.packageName)) {
7223                    iter.remove();
7224                }
7225            }
7226
7227            // Take care of first install / last update times.
7228            if (currentTime != 0) {
7229                if (pkgSetting.firstInstallTime == 0) {
7230                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7231                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7232                    pkgSetting.lastUpdateTime = currentTime;
7233                }
7234            } else if (pkgSetting.firstInstallTime == 0) {
7235                // We need *something*.  Take time time stamp of the file.
7236                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7237            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7238                if (scanFileTime != pkgSetting.timeStamp) {
7239                    // A package on the system image has changed; consider this
7240                    // to be an update.
7241                    pkgSetting.lastUpdateTime = scanFileTime;
7242                }
7243            }
7244
7245            // Add the package's KeySets to the global KeySetManagerService
7246            ksms.addScannedPackageLPw(pkg);
7247
7248            int N = pkg.providers.size();
7249            StringBuilder r = null;
7250            int i;
7251            for (i=0; i<N; i++) {
7252                PackageParser.Provider p = pkg.providers.get(i);
7253                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7254                        p.info.processName, pkg.applicationInfo.uid);
7255                mProviders.addProvider(p);
7256                p.syncable = p.info.isSyncable;
7257                if (p.info.authority != null) {
7258                    String names[] = p.info.authority.split(";");
7259                    p.info.authority = null;
7260                    for (int j = 0; j < names.length; j++) {
7261                        if (j == 1 && p.syncable) {
7262                            // We only want the first authority for a provider to possibly be
7263                            // syncable, so if we already added this provider using a different
7264                            // authority clear the syncable flag. We copy the provider before
7265                            // changing it because the mProviders object contains a reference
7266                            // to a provider that we don't want to change.
7267                            // Only do this for the second authority since the resulting provider
7268                            // object can be the same for all future authorities for this provider.
7269                            p = new PackageParser.Provider(p);
7270                            p.syncable = false;
7271                        }
7272                        if (!mProvidersByAuthority.containsKey(names[j])) {
7273                            mProvidersByAuthority.put(names[j], p);
7274                            if (p.info.authority == null) {
7275                                p.info.authority = names[j];
7276                            } else {
7277                                p.info.authority = p.info.authority + ";" + names[j];
7278                            }
7279                            if (DEBUG_PACKAGE_SCANNING) {
7280                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7281                                    Log.d(TAG, "Registered content provider: " + names[j]
7282                                            + ", className = " + p.info.name + ", isSyncable = "
7283                                            + p.info.isSyncable);
7284                            }
7285                        } else {
7286                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7287                            Slog.w(TAG, "Skipping provider name " + names[j] +
7288                                    " (in package " + pkg.applicationInfo.packageName +
7289                                    "): name already used by "
7290                                    + ((other != null && other.getComponentName() != null)
7291                                            ? other.getComponentName().getPackageName() : "?"));
7292                        }
7293                    }
7294                }
7295                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7296                    if (r == null) {
7297                        r = new StringBuilder(256);
7298                    } else {
7299                        r.append(' ');
7300                    }
7301                    r.append(p.info.name);
7302                }
7303            }
7304            if (r != null) {
7305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7306            }
7307
7308            N = pkg.services.size();
7309            r = null;
7310            for (i=0; i<N; i++) {
7311                PackageParser.Service s = pkg.services.get(i);
7312                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7313                        s.info.processName, pkg.applicationInfo.uid);
7314                mServices.addService(s);
7315                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7316                    if (r == null) {
7317                        r = new StringBuilder(256);
7318                    } else {
7319                        r.append(' ');
7320                    }
7321                    r.append(s.info.name);
7322                }
7323            }
7324            if (r != null) {
7325                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7326            }
7327
7328            N = pkg.receivers.size();
7329            r = null;
7330            for (i=0; i<N; i++) {
7331                PackageParser.Activity a = pkg.receivers.get(i);
7332                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7333                        a.info.processName, pkg.applicationInfo.uid);
7334                mReceivers.addActivity(a, "receiver");
7335                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7336                    if (r == null) {
7337                        r = new StringBuilder(256);
7338                    } else {
7339                        r.append(' ');
7340                    }
7341                    r.append(a.info.name);
7342                }
7343            }
7344            if (r != null) {
7345                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7346            }
7347
7348            N = pkg.activities.size();
7349            r = null;
7350            for (i=0; i<N; i++) {
7351                PackageParser.Activity a = pkg.activities.get(i);
7352                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7353                        a.info.processName, pkg.applicationInfo.uid);
7354                mActivities.addActivity(a, "activity");
7355                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7356                    if (r == null) {
7357                        r = new StringBuilder(256);
7358                    } else {
7359                        r.append(' ');
7360                    }
7361                    r.append(a.info.name);
7362                }
7363            }
7364            if (r != null) {
7365                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7366            }
7367
7368            N = pkg.permissionGroups.size();
7369            r = null;
7370            for (i=0; i<N; i++) {
7371                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7372                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7373                if (cur == null) {
7374                    mPermissionGroups.put(pg.info.name, pg);
7375                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7376                        if (r == null) {
7377                            r = new StringBuilder(256);
7378                        } else {
7379                            r.append(' ');
7380                        }
7381                        r.append(pg.info.name);
7382                    }
7383                } else {
7384                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7385                            + pg.info.packageName + " ignored: original from "
7386                            + cur.info.packageName);
7387                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7388                        if (r == null) {
7389                            r = new StringBuilder(256);
7390                        } else {
7391                            r.append(' ');
7392                        }
7393                        r.append("DUP:");
7394                        r.append(pg.info.name);
7395                    }
7396                }
7397            }
7398            if (r != null) {
7399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7400            }
7401
7402            N = pkg.permissions.size();
7403            r = null;
7404            for (i=0; i<N; i++) {
7405                PackageParser.Permission p = pkg.permissions.get(i);
7406
7407                // Assume by default that we did not install this permission into the system.
7408                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7409
7410                // Now that permission groups have a special meaning, we ignore permission
7411                // groups for legacy apps to prevent unexpected behavior. In particular,
7412                // permissions for one app being granted to someone just becuase they happen
7413                // to be in a group defined by another app (before this had no implications).
7414                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7415                    p.group = mPermissionGroups.get(p.info.group);
7416                    // Warn for a permission in an unknown group.
7417                    if (p.info.group != null && p.group == null) {
7418                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7419                                + p.info.packageName + " in an unknown group " + p.info.group);
7420                    }
7421                }
7422
7423                ArrayMap<String, BasePermission> permissionMap =
7424                        p.tree ? mSettings.mPermissionTrees
7425                                : mSettings.mPermissions;
7426                BasePermission bp = permissionMap.get(p.info.name);
7427
7428                // Allow system apps to redefine non-system permissions
7429                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7430                    final boolean currentOwnerIsSystem = (bp.perm != null
7431                            && isSystemApp(bp.perm.owner));
7432                    if (isSystemApp(p.owner)) {
7433                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7434                            // It's a built-in permission and no owner, take ownership now
7435                            bp.packageSetting = pkgSetting;
7436                            bp.perm = p;
7437                            bp.uid = pkg.applicationInfo.uid;
7438                            bp.sourcePackage = p.info.packageName;
7439                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7440                        } else if (!currentOwnerIsSystem) {
7441                            String msg = "New decl " + p.owner + " of permission  "
7442                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7443                            reportSettingsProblem(Log.WARN, msg);
7444                            bp = null;
7445                        }
7446                    }
7447                }
7448
7449                if (bp == null) {
7450                    bp = new BasePermission(p.info.name, p.info.packageName,
7451                            BasePermission.TYPE_NORMAL);
7452                    permissionMap.put(p.info.name, bp);
7453                }
7454
7455                if (bp.perm == null) {
7456                    if (bp.sourcePackage == null
7457                            || bp.sourcePackage.equals(p.info.packageName)) {
7458                        BasePermission tree = findPermissionTreeLP(p.info.name);
7459                        if (tree == null
7460                                || tree.sourcePackage.equals(p.info.packageName)) {
7461                            bp.packageSetting = pkgSetting;
7462                            bp.perm = p;
7463                            bp.uid = pkg.applicationInfo.uid;
7464                            bp.sourcePackage = p.info.packageName;
7465                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7466                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7467                                if (r == null) {
7468                                    r = new StringBuilder(256);
7469                                } else {
7470                                    r.append(' ');
7471                                }
7472                                r.append(p.info.name);
7473                            }
7474                        } else {
7475                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7476                                    + p.info.packageName + " ignored: base tree "
7477                                    + tree.name + " is from package "
7478                                    + tree.sourcePackage);
7479                        }
7480                    } else {
7481                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7482                                + p.info.packageName + " ignored: original from "
7483                                + bp.sourcePackage);
7484                    }
7485                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7486                    if (r == null) {
7487                        r = new StringBuilder(256);
7488                    } else {
7489                        r.append(' ');
7490                    }
7491                    r.append("DUP:");
7492                    r.append(p.info.name);
7493                }
7494                if (bp.perm == p) {
7495                    bp.protectionLevel = p.info.protectionLevel;
7496                }
7497            }
7498
7499            if (r != null) {
7500                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7501            }
7502
7503            N = pkg.instrumentation.size();
7504            r = null;
7505            for (i=0; i<N; i++) {
7506                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7507                a.info.packageName = pkg.applicationInfo.packageName;
7508                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7509                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7510                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7511                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7512                a.info.dataDir = pkg.applicationInfo.dataDir;
7513
7514                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7515                // need other information about the application, like the ABI and what not ?
7516                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7517                mInstrumentation.put(a.getComponentName(), a);
7518                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7519                    if (r == null) {
7520                        r = new StringBuilder(256);
7521                    } else {
7522                        r.append(' ');
7523                    }
7524                    r.append(a.info.name);
7525                }
7526            }
7527            if (r != null) {
7528                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7529            }
7530
7531            if (pkg.protectedBroadcasts != null) {
7532                N = pkg.protectedBroadcasts.size();
7533                for (i=0; i<N; i++) {
7534                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7535                }
7536            }
7537
7538            pkgSetting.setTimeStamp(scanFileTime);
7539
7540            // Create idmap files for pairs of (packages, overlay packages).
7541            // Note: "android", ie framework-res.apk, is handled by native layers.
7542            if (pkg.mOverlayTarget != null) {
7543                // This is an overlay package.
7544                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7545                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7546                        mOverlays.put(pkg.mOverlayTarget,
7547                                new ArrayMap<String, PackageParser.Package>());
7548                    }
7549                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7550                    map.put(pkg.packageName, pkg);
7551                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7552                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7553                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7554                                "scanPackageLI failed to createIdmap");
7555                    }
7556                }
7557            } else if (mOverlays.containsKey(pkg.packageName) &&
7558                    !pkg.packageName.equals("android")) {
7559                // This is a regular package, with one or more known overlay packages.
7560                createIdmapsForPackageLI(pkg);
7561            }
7562        }
7563
7564        return pkg;
7565    }
7566
7567    /**
7568     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7569     * is derived purely on the basis of the contents of {@code scanFile} and
7570     * {@code cpuAbiOverride}.
7571     *
7572     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7573     */
7574    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7575                                 String cpuAbiOverride, boolean extractLibs)
7576            throws PackageManagerException {
7577        // TODO: We can probably be smarter about this stuff. For installed apps,
7578        // we can calculate this information at install time once and for all. For
7579        // system apps, we can probably assume that this information doesn't change
7580        // after the first boot scan. As things stand, we do lots of unnecessary work.
7581
7582        // Give ourselves some initial paths; we'll come back for another
7583        // pass once we've determined ABI below.
7584        setNativeLibraryPaths(pkg);
7585
7586        // We would never need to extract libs for forward-locked and external packages,
7587        // since the container service will do it for us. We shouldn't attempt to
7588        // extract libs from system app when it was not updated.
7589        if (pkg.isForwardLocked() || isExternal(pkg) ||
7590            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7591            extractLibs = false;
7592        }
7593
7594        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7595        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7596
7597        NativeLibraryHelper.Handle handle = null;
7598        try {
7599            handle = NativeLibraryHelper.Handle.create(scanFile);
7600            // TODO(multiArch): This can be null for apps that didn't go through the
7601            // usual installation process. We can calculate it again, like we
7602            // do during install time.
7603            //
7604            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7605            // unnecessary.
7606            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7607
7608            // Null out the abis so that they can be recalculated.
7609            pkg.applicationInfo.primaryCpuAbi = null;
7610            pkg.applicationInfo.secondaryCpuAbi = null;
7611            if (isMultiArch(pkg.applicationInfo)) {
7612                // Warn if we've set an abiOverride for multi-lib packages..
7613                // By definition, we need to copy both 32 and 64 bit libraries for
7614                // such packages.
7615                if (pkg.cpuAbiOverride != null
7616                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7617                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7618                }
7619
7620                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7621                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7622                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7623                    if (extractLibs) {
7624                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7625                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7626                                useIsaSpecificSubdirs);
7627                    } else {
7628                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7629                    }
7630                }
7631
7632                maybeThrowExceptionForMultiArchCopy(
7633                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7634
7635                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7636                    if (extractLibs) {
7637                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7638                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7639                                useIsaSpecificSubdirs);
7640                    } else {
7641                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7642                    }
7643                }
7644
7645                maybeThrowExceptionForMultiArchCopy(
7646                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7647
7648                if (abi64 >= 0) {
7649                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7650                }
7651
7652                if (abi32 >= 0) {
7653                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7654                    if (abi64 >= 0) {
7655                        pkg.applicationInfo.secondaryCpuAbi = abi;
7656                    } else {
7657                        pkg.applicationInfo.primaryCpuAbi = abi;
7658                    }
7659                }
7660            } else {
7661                String[] abiList = (cpuAbiOverride != null) ?
7662                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7663
7664                // Enable gross and lame hacks for apps that are built with old
7665                // SDK tools. We must scan their APKs for renderscript bitcode and
7666                // not launch them if it's present. Don't bother checking on devices
7667                // that don't have 64 bit support.
7668                boolean needsRenderScriptOverride = false;
7669                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7670                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7671                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7672                    needsRenderScriptOverride = true;
7673                }
7674
7675                final int copyRet;
7676                if (extractLibs) {
7677                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7678                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7679                } else {
7680                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7681                }
7682
7683                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7684                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7685                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7686                }
7687
7688                if (copyRet >= 0) {
7689                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7690                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7691                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7692                } else if (needsRenderScriptOverride) {
7693                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7694                }
7695            }
7696        } catch (IOException ioe) {
7697            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7698        } finally {
7699            IoUtils.closeQuietly(handle);
7700        }
7701
7702        // Now that we've calculated the ABIs and determined if it's an internal app,
7703        // we will go ahead and populate the nativeLibraryPath.
7704        setNativeLibraryPaths(pkg);
7705    }
7706
7707    /**
7708     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7709     * i.e, so that all packages can be run inside a single process if required.
7710     *
7711     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7712     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7713     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7714     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7715     * updating a package that belongs to a shared user.
7716     *
7717     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7718     * adds unnecessary complexity.
7719     */
7720    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7721            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7722        String requiredInstructionSet = null;
7723        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7724            requiredInstructionSet = VMRuntime.getInstructionSet(
7725                     scannedPackage.applicationInfo.primaryCpuAbi);
7726        }
7727
7728        PackageSetting requirer = null;
7729        for (PackageSetting ps : packagesForUser) {
7730            // If packagesForUser contains scannedPackage, we skip it. This will happen
7731            // when scannedPackage is an update of an existing package. Without this check,
7732            // we will never be able to change the ABI of any package belonging to a shared
7733            // user, even if it's compatible with other packages.
7734            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7735                if (ps.primaryCpuAbiString == null) {
7736                    continue;
7737                }
7738
7739                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7740                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7741                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7742                    // this but there's not much we can do.
7743                    String errorMessage = "Instruction set mismatch, "
7744                            + ((requirer == null) ? "[caller]" : requirer)
7745                            + " requires " + requiredInstructionSet + " whereas " + ps
7746                            + " requires " + instructionSet;
7747                    Slog.w(TAG, errorMessage);
7748                }
7749
7750                if (requiredInstructionSet == null) {
7751                    requiredInstructionSet = instructionSet;
7752                    requirer = ps;
7753                }
7754            }
7755        }
7756
7757        if (requiredInstructionSet != null) {
7758            String adjustedAbi;
7759            if (requirer != null) {
7760                // requirer != null implies that either scannedPackage was null or that scannedPackage
7761                // did not require an ABI, in which case we have to adjust scannedPackage to match
7762                // the ABI of the set (which is the same as requirer's ABI)
7763                adjustedAbi = requirer.primaryCpuAbiString;
7764                if (scannedPackage != null) {
7765                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7766                }
7767            } else {
7768                // requirer == null implies that we're updating all ABIs in the set to
7769                // match scannedPackage.
7770                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7771            }
7772
7773            for (PackageSetting ps : packagesForUser) {
7774                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7775                    if (ps.primaryCpuAbiString != null) {
7776                        continue;
7777                    }
7778
7779                    ps.primaryCpuAbiString = adjustedAbi;
7780                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7781                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7782                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7783
7784                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7785                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7786                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7787                            ps.primaryCpuAbiString = null;
7788                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7789                            return;
7790                        } else {
7791                            mInstaller.rmdex(ps.codePathString,
7792                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7793                        }
7794                    }
7795                }
7796            }
7797        }
7798    }
7799
7800    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7801        synchronized (mPackages) {
7802            mResolverReplaced = true;
7803            // Set up information for custom user intent resolution activity.
7804            mResolveActivity.applicationInfo = pkg.applicationInfo;
7805            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7806            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7807            mResolveActivity.processName = pkg.applicationInfo.packageName;
7808            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7809            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7810                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7811            mResolveActivity.theme = 0;
7812            mResolveActivity.exported = true;
7813            mResolveActivity.enabled = true;
7814            mResolveInfo.activityInfo = mResolveActivity;
7815            mResolveInfo.priority = 0;
7816            mResolveInfo.preferredOrder = 0;
7817            mResolveInfo.match = 0;
7818            mResolveComponentName = mCustomResolverComponentName;
7819            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7820                    mResolveComponentName);
7821        }
7822    }
7823
7824    private static String calculateBundledApkRoot(final String codePathString) {
7825        final File codePath = new File(codePathString);
7826        final File codeRoot;
7827        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7828            codeRoot = Environment.getRootDirectory();
7829        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7830            codeRoot = Environment.getOemDirectory();
7831        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7832            codeRoot = Environment.getVendorDirectory();
7833        } else {
7834            // Unrecognized code path; take its top real segment as the apk root:
7835            // e.g. /something/app/blah.apk => /something
7836            try {
7837                File f = codePath.getCanonicalFile();
7838                File parent = f.getParentFile();    // non-null because codePath is a file
7839                File tmp;
7840                while ((tmp = parent.getParentFile()) != null) {
7841                    f = parent;
7842                    parent = tmp;
7843                }
7844                codeRoot = f;
7845                Slog.w(TAG, "Unrecognized code path "
7846                        + codePath + " - using " + codeRoot);
7847            } catch (IOException e) {
7848                // Can't canonicalize the code path -- shenanigans?
7849                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7850                return Environment.getRootDirectory().getPath();
7851            }
7852        }
7853        return codeRoot.getPath();
7854    }
7855
7856    /**
7857     * Derive and set the location of native libraries for the given package,
7858     * which varies depending on where and how the package was installed.
7859     */
7860    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7861        final ApplicationInfo info = pkg.applicationInfo;
7862        final String codePath = pkg.codePath;
7863        final File codeFile = new File(codePath);
7864        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7865        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7866
7867        info.nativeLibraryRootDir = null;
7868        info.nativeLibraryRootRequiresIsa = false;
7869        info.nativeLibraryDir = null;
7870        info.secondaryNativeLibraryDir = null;
7871
7872        if (isApkFile(codeFile)) {
7873            // Monolithic install
7874            if (bundledApp) {
7875                // If "/system/lib64/apkname" exists, assume that is the per-package
7876                // native library directory to use; otherwise use "/system/lib/apkname".
7877                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7878                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7879                        getPrimaryInstructionSet(info));
7880
7881                // This is a bundled system app so choose the path based on the ABI.
7882                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7883                // is just the default path.
7884                final String apkName = deriveCodePathName(codePath);
7885                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7886                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7887                        apkName).getAbsolutePath();
7888
7889                if (info.secondaryCpuAbi != null) {
7890                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7891                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7892                            secondaryLibDir, apkName).getAbsolutePath();
7893                }
7894            } else if (asecApp) {
7895                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7896                        .getAbsolutePath();
7897            } else {
7898                final String apkName = deriveCodePathName(codePath);
7899                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7900                        .getAbsolutePath();
7901            }
7902
7903            info.nativeLibraryRootRequiresIsa = false;
7904            info.nativeLibraryDir = info.nativeLibraryRootDir;
7905        } else {
7906            // Cluster install
7907            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7908            info.nativeLibraryRootRequiresIsa = true;
7909
7910            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7911                    getPrimaryInstructionSet(info)).getAbsolutePath();
7912
7913            if (info.secondaryCpuAbi != null) {
7914                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7915                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7916            }
7917        }
7918    }
7919
7920    /**
7921     * Calculate the abis and roots for a bundled app. These can uniquely
7922     * be determined from the contents of the system partition, i.e whether
7923     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7924     * of this information, and instead assume that the system was built
7925     * sensibly.
7926     */
7927    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7928                                           PackageSetting pkgSetting) {
7929        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7930
7931        // If "/system/lib64/apkname" exists, assume that is the per-package
7932        // native library directory to use; otherwise use "/system/lib/apkname".
7933        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7934        setBundledAppAbi(pkg, apkRoot, apkName);
7935        // pkgSetting might be null during rescan following uninstall of updates
7936        // to a bundled app, so accommodate that possibility.  The settings in
7937        // that case will be established later from the parsed package.
7938        //
7939        // If the settings aren't null, sync them up with what we've just derived.
7940        // note that apkRoot isn't stored in the package settings.
7941        if (pkgSetting != null) {
7942            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7943            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7944        }
7945    }
7946
7947    /**
7948     * Deduces the ABI of a bundled app and sets the relevant fields on the
7949     * parsed pkg object.
7950     *
7951     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7952     *        under which system libraries are installed.
7953     * @param apkName the name of the installed package.
7954     */
7955    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7956        final File codeFile = new File(pkg.codePath);
7957
7958        final boolean has64BitLibs;
7959        final boolean has32BitLibs;
7960        if (isApkFile(codeFile)) {
7961            // Monolithic install
7962            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7963            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7964        } else {
7965            // Cluster install
7966            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7967            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7968                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7969                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7970                has64BitLibs = (new File(rootDir, isa)).exists();
7971            } else {
7972                has64BitLibs = false;
7973            }
7974            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7975                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7976                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7977                has32BitLibs = (new File(rootDir, isa)).exists();
7978            } else {
7979                has32BitLibs = false;
7980            }
7981        }
7982
7983        if (has64BitLibs && !has32BitLibs) {
7984            // The package has 64 bit libs, but not 32 bit libs. Its primary
7985            // ABI should be 64 bit. We can safely assume here that the bundled
7986            // native libraries correspond to the most preferred ABI in the list.
7987
7988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7989            pkg.applicationInfo.secondaryCpuAbi = null;
7990        } else if (has32BitLibs && !has64BitLibs) {
7991            // The package has 32 bit libs but not 64 bit libs. Its primary
7992            // ABI should be 32 bit.
7993
7994            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7995            pkg.applicationInfo.secondaryCpuAbi = null;
7996        } else if (has32BitLibs && has64BitLibs) {
7997            // The application has both 64 and 32 bit bundled libraries. We check
7998            // here that the app declares multiArch support, and warn if it doesn't.
7999            //
8000            // We will be lenient here and record both ABIs. The primary will be the
8001            // ABI that's higher on the list, i.e, a device that's configured to prefer
8002            // 64 bit apps will see a 64 bit primary ABI,
8003
8004            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8005                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8006            }
8007
8008            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8009                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8010                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8011            } else {
8012                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8013                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8014            }
8015        } else {
8016            pkg.applicationInfo.primaryCpuAbi = null;
8017            pkg.applicationInfo.secondaryCpuAbi = null;
8018        }
8019    }
8020
8021    private void killApplication(String pkgName, int appId, String reason) {
8022        // Request the ActivityManager to kill the process(only for existing packages)
8023        // so that we do not end up in a confused state while the user is still using the older
8024        // version of the application while the new one gets installed.
8025        IActivityManager am = ActivityManagerNative.getDefault();
8026        if (am != null) {
8027            try {
8028                am.killApplicationWithAppId(pkgName, appId, reason);
8029            } catch (RemoteException e) {
8030            }
8031        }
8032    }
8033
8034    void removePackageLI(PackageSetting ps, boolean chatty) {
8035        if (DEBUG_INSTALL) {
8036            if (chatty)
8037                Log.d(TAG, "Removing package " + ps.name);
8038        }
8039
8040        // writer
8041        synchronized (mPackages) {
8042            mPackages.remove(ps.name);
8043            final PackageParser.Package pkg = ps.pkg;
8044            if (pkg != null) {
8045                cleanPackageDataStructuresLILPw(pkg, chatty);
8046            }
8047        }
8048    }
8049
8050    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8051        if (DEBUG_INSTALL) {
8052            if (chatty)
8053                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8054        }
8055
8056        // writer
8057        synchronized (mPackages) {
8058            mPackages.remove(pkg.applicationInfo.packageName);
8059            cleanPackageDataStructuresLILPw(pkg, chatty);
8060        }
8061    }
8062
8063    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8064        int N = pkg.providers.size();
8065        StringBuilder r = null;
8066        int i;
8067        for (i=0; i<N; i++) {
8068            PackageParser.Provider p = pkg.providers.get(i);
8069            mProviders.removeProvider(p);
8070            if (p.info.authority == null) {
8071
8072                /* There was another ContentProvider with this authority when
8073                 * this app was installed so this authority is null,
8074                 * Ignore it as we don't have to unregister the provider.
8075                 */
8076                continue;
8077            }
8078            String names[] = p.info.authority.split(";");
8079            for (int j = 0; j < names.length; j++) {
8080                if (mProvidersByAuthority.get(names[j]) == p) {
8081                    mProvidersByAuthority.remove(names[j]);
8082                    if (DEBUG_REMOVE) {
8083                        if (chatty)
8084                            Log.d(TAG, "Unregistered content provider: " + names[j]
8085                                    + ", className = " + p.info.name + ", isSyncable = "
8086                                    + p.info.isSyncable);
8087                    }
8088                }
8089            }
8090            if (DEBUG_REMOVE && chatty) {
8091                if (r == null) {
8092                    r = new StringBuilder(256);
8093                } else {
8094                    r.append(' ');
8095                }
8096                r.append(p.info.name);
8097            }
8098        }
8099        if (r != null) {
8100            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8101        }
8102
8103        N = pkg.services.size();
8104        r = null;
8105        for (i=0; i<N; i++) {
8106            PackageParser.Service s = pkg.services.get(i);
8107            mServices.removeService(s);
8108            if (chatty) {
8109                if (r == null) {
8110                    r = new StringBuilder(256);
8111                } else {
8112                    r.append(' ');
8113                }
8114                r.append(s.info.name);
8115            }
8116        }
8117        if (r != null) {
8118            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8119        }
8120
8121        N = pkg.receivers.size();
8122        r = null;
8123        for (i=0; i<N; i++) {
8124            PackageParser.Activity a = pkg.receivers.get(i);
8125            mReceivers.removeActivity(a, "receiver");
8126            if (DEBUG_REMOVE && chatty) {
8127                if (r == null) {
8128                    r = new StringBuilder(256);
8129                } else {
8130                    r.append(' ');
8131                }
8132                r.append(a.info.name);
8133            }
8134        }
8135        if (r != null) {
8136            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8137        }
8138
8139        N = pkg.activities.size();
8140        r = null;
8141        for (i=0; i<N; i++) {
8142            PackageParser.Activity a = pkg.activities.get(i);
8143            mActivities.removeActivity(a, "activity");
8144            if (DEBUG_REMOVE && chatty) {
8145                if (r == null) {
8146                    r = new StringBuilder(256);
8147                } else {
8148                    r.append(' ');
8149                }
8150                r.append(a.info.name);
8151            }
8152        }
8153        if (r != null) {
8154            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8155        }
8156
8157        N = pkg.permissions.size();
8158        r = null;
8159        for (i=0; i<N; i++) {
8160            PackageParser.Permission p = pkg.permissions.get(i);
8161            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8162            if (bp == null) {
8163                bp = mSettings.mPermissionTrees.get(p.info.name);
8164            }
8165            if (bp != null && bp.perm == p) {
8166                bp.perm = null;
8167                if (DEBUG_REMOVE && chatty) {
8168                    if (r == null) {
8169                        r = new StringBuilder(256);
8170                    } else {
8171                        r.append(' ');
8172                    }
8173                    r.append(p.info.name);
8174                }
8175            }
8176            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8177                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8178                if (appOpPerms != null) {
8179                    appOpPerms.remove(pkg.packageName);
8180                }
8181            }
8182        }
8183        if (r != null) {
8184            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8185        }
8186
8187        N = pkg.requestedPermissions.size();
8188        r = null;
8189        for (i=0; i<N; i++) {
8190            String perm = pkg.requestedPermissions.get(i);
8191            BasePermission bp = mSettings.mPermissions.get(perm);
8192            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8193                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8194                if (appOpPerms != null) {
8195                    appOpPerms.remove(pkg.packageName);
8196                    if (appOpPerms.isEmpty()) {
8197                        mAppOpPermissionPackages.remove(perm);
8198                    }
8199                }
8200            }
8201        }
8202        if (r != null) {
8203            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8204        }
8205
8206        N = pkg.instrumentation.size();
8207        r = null;
8208        for (i=0; i<N; i++) {
8209            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8210            mInstrumentation.remove(a.getComponentName());
8211            if (DEBUG_REMOVE && chatty) {
8212                if (r == null) {
8213                    r = new StringBuilder(256);
8214                } else {
8215                    r.append(' ');
8216                }
8217                r.append(a.info.name);
8218            }
8219        }
8220        if (r != null) {
8221            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8222        }
8223
8224        r = null;
8225        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8226            // Only system apps can hold shared libraries.
8227            if (pkg.libraryNames != null) {
8228                for (i=0; i<pkg.libraryNames.size(); i++) {
8229                    String name = pkg.libraryNames.get(i);
8230                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8231                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8232                        mSharedLibraries.remove(name);
8233                        if (DEBUG_REMOVE && chatty) {
8234                            if (r == null) {
8235                                r = new StringBuilder(256);
8236                            } else {
8237                                r.append(' ');
8238                            }
8239                            r.append(name);
8240                        }
8241                    }
8242                }
8243            }
8244        }
8245        if (r != null) {
8246            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8247        }
8248    }
8249
8250    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8251        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8252            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8253                return true;
8254            }
8255        }
8256        return false;
8257    }
8258
8259    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8260    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8261    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8262
8263    private void updatePermissionsLPw(String changingPkg,
8264            PackageParser.Package pkgInfo, int flags) {
8265        // Make sure there are no dangling permission trees.
8266        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8267        while (it.hasNext()) {
8268            final BasePermission bp = it.next();
8269            if (bp.packageSetting == null) {
8270                // We may not yet have parsed the package, so just see if
8271                // we still know about its settings.
8272                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8273            }
8274            if (bp.packageSetting == null) {
8275                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8276                        + " from package " + bp.sourcePackage);
8277                it.remove();
8278            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8279                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8280                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8281                            + " from package " + bp.sourcePackage);
8282                    flags |= UPDATE_PERMISSIONS_ALL;
8283                    it.remove();
8284                }
8285            }
8286        }
8287
8288        // Make sure all dynamic permissions have been assigned to a package,
8289        // and make sure there are no dangling permissions.
8290        it = mSettings.mPermissions.values().iterator();
8291        while (it.hasNext()) {
8292            final BasePermission bp = it.next();
8293            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8294                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8295                        + bp.name + " pkg=" + bp.sourcePackage
8296                        + " info=" + bp.pendingInfo);
8297                if (bp.packageSetting == null && bp.pendingInfo != null) {
8298                    final BasePermission tree = findPermissionTreeLP(bp.name);
8299                    if (tree != null && tree.perm != null) {
8300                        bp.packageSetting = tree.packageSetting;
8301                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8302                                new PermissionInfo(bp.pendingInfo));
8303                        bp.perm.info.packageName = tree.perm.info.packageName;
8304                        bp.perm.info.name = bp.name;
8305                        bp.uid = tree.uid;
8306                    }
8307                }
8308            }
8309            if (bp.packageSetting == null) {
8310                // We may not yet have parsed the package, so just see if
8311                // we still know about its settings.
8312                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8313            }
8314            if (bp.packageSetting == null) {
8315                Slog.w(TAG, "Removing dangling permission: " + bp.name
8316                        + " from package " + bp.sourcePackage);
8317                it.remove();
8318            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8319                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8320                    Slog.i(TAG, "Removing old permission: " + bp.name
8321                            + " from package " + bp.sourcePackage);
8322                    flags |= UPDATE_PERMISSIONS_ALL;
8323                    it.remove();
8324                }
8325            }
8326        }
8327
8328        // Now update the permissions for all packages, in particular
8329        // replace the granted permissions of the system packages.
8330        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8331            for (PackageParser.Package pkg : mPackages.values()) {
8332                if (pkg != pkgInfo) {
8333                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8334                            changingPkg);
8335                }
8336            }
8337        }
8338
8339        if (pkgInfo != null) {
8340            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8341        }
8342    }
8343
8344    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8345            String packageOfInterest) {
8346        // IMPORTANT: There are two types of permissions: install and runtime.
8347        // Install time permissions are granted when the app is installed to
8348        // all device users and users added in the future. Runtime permissions
8349        // are granted at runtime explicitly to specific users. Normal and signature
8350        // protected permissions are install time permissions. Dangerous permissions
8351        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8352        // otherwise they are runtime permissions. This function does not manage
8353        // runtime permissions except for the case an app targeting Lollipop MR1
8354        // being upgraded to target a newer SDK, in which case dangerous permissions
8355        // are transformed from install time to runtime ones.
8356
8357        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8358        if (ps == null) {
8359            return;
8360        }
8361
8362        PermissionsState permissionsState = ps.getPermissionsState();
8363        PermissionsState origPermissions = permissionsState;
8364
8365        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8366
8367        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8368
8369        boolean changedInstallPermission = false;
8370
8371        if (replace) {
8372            ps.installPermissionsFixed = false;
8373            if (!ps.isSharedUser()) {
8374                origPermissions = new PermissionsState(permissionsState);
8375                permissionsState.reset();
8376            }
8377        }
8378
8379        permissionsState.setGlobalGids(mGlobalGids);
8380
8381        final int N = pkg.requestedPermissions.size();
8382        for (int i=0; i<N; i++) {
8383            final String name = pkg.requestedPermissions.get(i);
8384            final BasePermission bp = mSettings.mPermissions.get(name);
8385
8386            if (DEBUG_INSTALL) {
8387                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8388            }
8389
8390            if (bp == null || bp.packageSetting == null) {
8391                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8392                    Slog.w(TAG, "Unknown permission " + name
8393                            + " in package " + pkg.packageName);
8394                }
8395                continue;
8396            }
8397
8398            final String perm = bp.name;
8399            boolean allowedSig = false;
8400            int grant = GRANT_DENIED;
8401
8402            // Keep track of app op permissions.
8403            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8404                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8405                if (pkgs == null) {
8406                    pkgs = new ArraySet<>();
8407                    mAppOpPermissionPackages.put(bp.name, pkgs);
8408                }
8409                pkgs.add(pkg.packageName);
8410            }
8411
8412            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8413            switch (level) {
8414                case PermissionInfo.PROTECTION_NORMAL: {
8415                    // For all apps normal permissions are install time ones.
8416                    grant = GRANT_INSTALL;
8417                } break;
8418
8419                case PermissionInfo.PROTECTION_DANGEROUS: {
8420                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8421                        // For legacy apps dangerous permissions are install time ones.
8422                        grant = GRANT_INSTALL_LEGACY;
8423                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8424                        // For legacy apps that became modern, install becomes runtime.
8425                        grant = GRANT_UPGRADE;
8426                    } else if (mPromoteSystemApps
8427                            && isSystemApp(ps)
8428                            && mExistingSystemPackages.contains(ps.name)) {
8429                        // For legacy system apps, install becomes runtime.
8430                        // We cannot check hasInstallPermission() for system apps since those
8431                        // permissions were granted implicitly and not persisted pre-M.
8432                        grant = GRANT_UPGRADE;
8433                    } else {
8434                        // For modern apps keep runtime permissions unchanged.
8435                        grant = GRANT_RUNTIME;
8436                    }
8437                } break;
8438
8439                case PermissionInfo.PROTECTION_SIGNATURE: {
8440                    // For all apps signature permissions are install time ones.
8441                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8442                    if (allowedSig) {
8443                        grant = GRANT_INSTALL;
8444                    }
8445                } break;
8446            }
8447
8448            if (DEBUG_INSTALL) {
8449                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8450            }
8451
8452            if (grant != GRANT_DENIED) {
8453                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8454                    // If this is an existing, non-system package, then
8455                    // we can't add any new permissions to it.
8456                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8457                        // Except...  if this is a permission that was added
8458                        // to the platform (note: need to only do this when
8459                        // updating the platform).
8460                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8461                            grant = GRANT_DENIED;
8462                        }
8463                    }
8464                }
8465
8466                switch (grant) {
8467                    case GRANT_INSTALL: {
8468                        // Revoke this as runtime permission to handle the case of
8469                        // a runtime permission being downgraded to an install one.
8470                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8471                            if (origPermissions.getRuntimePermissionState(
8472                                    bp.name, userId) != null) {
8473                                // Revoke the runtime permission and clear the flags.
8474                                origPermissions.revokeRuntimePermission(bp, userId);
8475                                origPermissions.updatePermissionFlags(bp, userId,
8476                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8477                                // If we revoked a permission permission, we have to write.
8478                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8479                                        changedRuntimePermissionUserIds, userId);
8480                            }
8481                        }
8482                        // Grant an install permission.
8483                        if (permissionsState.grantInstallPermission(bp) !=
8484                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8485                            changedInstallPermission = true;
8486                        }
8487                    } break;
8488
8489                    case GRANT_INSTALL_LEGACY: {
8490                        // Grant an install permission.
8491                        if (permissionsState.grantInstallPermission(bp) !=
8492                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8493                            changedInstallPermission = true;
8494                        }
8495                    } break;
8496
8497                    case GRANT_RUNTIME: {
8498                        // Grant previously granted runtime permissions.
8499                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8500                            PermissionState permissionState = origPermissions
8501                                    .getRuntimePermissionState(bp.name, userId);
8502                            final int flags = permissionState != null
8503                                    ? permissionState.getFlags() : 0;
8504                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8505                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8506                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8507                                    // If we cannot put the permission as it was, we have to write.
8508                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8509                                            changedRuntimePermissionUserIds, userId);
8510                                }
8511                            }
8512                            // Propagate the permission flags.
8513                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8514                        }
8515                    } break;
8516
8517                    case GRANT_UPGRADE: {
8518                        // Grant runtime permissions for a previously held install permission.
8519                        PermissionState permissionState = origPermissions
8520                                .getInstallPermissionState(bp.name);
8521                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8522
8523                        if (origPermissions.revokeInstallPermission(bp)
8524                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8525                            // We will be transferring the permission flags, so clear them.
8526                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8527                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8528                            changedInstallPermission = true;
8529                        }
8530
8531                        // If the permission is not to be promoted to runtime we ignore it and
8532                        // also its other flags as they are not applicable to install permissions.
8533                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8534                            for (int userId : currentUserIds) {
8535                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8536                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8537                                    // Transfer the permission flags.
8538                                    permissionsState.updatePermissionFlags(bp, userId,
8539                                            flags, flags);
8540                                    // If we granted the permission, we have to write.
8541                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8542                                            changedRuntimePermissionUserIds, userId);
8543                                }
8544                            }
8545                        }
8546                    } break;
8547
8548                    default: {
8549                        if (packageOfInterest == null
8550                                || packageOfInterest.equals(pkg.packageName)) {
8551                            Slog.w(TAG, "Not granting permission " + perm
8552                                    + " to package " + pkg.packageName
8553                                    + " because it was previously installed without");
8554                        }
8555                    } break;
8556                }
8557            } else {
8558                if (permissionsState.revokeInstallPermission(bp) !=
8559                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8560                    // Also drop the permission flags.
8561                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8562                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8563                    changedInstallPermission = true;
8564                    Slog.i(TAG, "Un-granting permission " + perm
8565                            + " from package " + pkg.packageName
8566                            + " (protectionLevel=" + bp.protectionLevel
8567                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8568                            + ")");
8569                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8570                    // Don't print warning for app op permissions, since it is fine for them
8571                    // not to be granted, there is a UI for the user to decide.
8572                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8573                        Slog.w(TAG, "Not granting permission " + perm
8574                                + " to package " + pkg.packageName
8575                                + " (protectionLevel=" + bp.protectionLevel
8576                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8577                                + ")");
8578                    }
8579                }
8580            }
8581        }
8582
8583        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8584                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8585            // This is the first that we have heard about this package, so the
8586            // permissions we have now selected are fixed until explicitly
8587            // changed.
8588            ps.installPermissionsFixed = true;
8589        }
8590
8591        // Persist the runtime permissions state for users with changes.
8592        for (int userId : changedRuntimePermissionUserIds) {
8593            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8594        }
8595    }
8596
8597    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8598        boolean allowed = false;
8599        final int NP = PackageParser.NEW_PERMISSIONS.length;
8600        for (int ip=0; ip<NP; ip++) {
8601            final PackageParser.NewPermissionInfo npi
8602                    = PackageParser.NEW_PERMISSIONS[ip];
8603            if (npi.name.equals(perm)
8604                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8605                allowed = true;
8606                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8607                        + pkg.packageName);
8608                break;
8609            }
8610        }
8611        return allowed;
8612    }
8613
8614    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8615            BasePermission bp, PermissionsState origPermissions) {
8616        boolean allowed;
8617        allowed = (compareSignatures(
8618                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8619                        == PackageManager.SIGNATURE_MATCH)
8620                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8621                        == PackageManager.SIGNATURE_MATCH);
8622        if (!allowed && (bp.protectionLevel
8623                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8624            if (isSystemApp(pkg)) {
8625                // For updated system applications, a system permission
8626                // is granted only if it had been defined by the original application.
8627                if (pkg.isUpdatedSystemApp()) {
8628                    final PackageSetting sysPs = mSettings
8629                            .getDisabledSystemPkgLPr(pkg.packageName);
8630                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8631                        // If the original was granted this permission, we take
8632                        // that grant decision as read and propagate it to the
8633                        // update.
8634                        if (sysPs.isPrivileged()) {
8635                            allowed = true;
8636                        }
8637                    } else {
8638                        // The system apk may have been updated with an older
8639                        // version of the one on the data partition, but which
8640                        // granted a new system permission that it didn't have
8641                        // before.  In this case we do want to allow the app to
8642                        // now get the new permission if the ancestral apk is
8643                        // privileged to get it.
8644                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8645                            for (int j=0;
8646                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8647                                if (perm.equals(
8648                                        sysPs.pkg.requestedPermissions.get(j))) {
8649                                    allowed = true;
8650                                    break;
8651                                }
8652                            }
8653                        }
8654                    }
8655                } else {
8656                    allowed = isPrivilegedApp(pkg);
8657                }
8658            }
8659        }
8660        if (!allowed) {
8661            if (!allowed && (bp.protectionLevel
8662                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8663                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8664                // If this was a previously normal/dangerous permission that got moved
8665                // to a system permission as part of the runtime permission redesign, then
8666                // we still want to blindly grant it to old apps.
8667                allowed = true;
8668            }
8669            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8670                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8671                // If this permission is to be granted to the system installer and
8672                // this app is an installer, then it gets the permission.
8673                allowed = true;
8674            }
8675            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8676                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8677                // If this permission is to be granted to the system verifier and
8678                // this app is a verifier, then it gets the permission.
8679                allowed = true;
8680            }
8681            if (!allowed && (bp.protectionLevel
8682                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8683                    && isSystemApp(pkg)) {
8684                // Any pre-installed system app is allowed to get this permission.
8685                allowed = true;
8686            }
8687            if (!allowed && (bp.protectionLevel
8688                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8689                // For development permissions, a development permission
8690                // is granted only if it was already granted.
8691                allowed = origPermissions.hasInstallPermission(perm);
8692            }
8693        }
8694        return allowed;
8695    }
8696
8697    final class ActivityIntentResolver
8698            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8699        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8700                boolean defaultOnly, int userId) {
8701            if (!sUserManager.exists(userId)) return null;
8702            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8703            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8704        }
8705
8706        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8707                int userId) {
8708            if (!sUserManager.exists(userId)) return null;
8709            mFlags = flags;
8710            return super.queryIntent(intent, resolvedType,
8711                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8712        }
8713
8714        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8715                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8716            if (!sUserManager.exists(userId)) return null;
8717            if (packageActivities == null) {
8718                return null;
8719            }
8720            mFlags = flags;
8721            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8722            final int N = packageActivities.size();
8723            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8724                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8725
8726            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8727            for (int i = 0; i < N; ++i) {
8728                intentFilters = packageActivities.get(i).intents;
8729                if (intentFilters != null && intentFilters.size() > 0) {
8730                    PackageParser.ActivityIntentInfo[] array =
8731                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8732                    intentFilters.toArray(array);
8733                    listCut.add(array);
8734                }
8735            }
8736            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8737        }
8738
8739        public final void addActivity(PackageParser.Activity a, String type) {
8740            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8741            mActivities.put(a.getComponentName(), a);
8742            if (DEBUG_SHOW_INFO)
8743                Log.v(
8744                TAG, "  " + type + " " +
8745                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8746            if (DEBUG_SHOW_INFO)
8747                Log.v(TAG, "    Class=" + a.info.name);
8748            final int NI = a.intents.size();
8749            for (int j=0; j<NI; j++) {
8750                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8751                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8752                    intent.setPriority(0);
8753                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8754                            + a.className + " with priority > 0, forcing to 0");
8755                }
8756                if (DEBUG_SHOW_INFO) {
8757                    Log.v(TAG, "    IntentFilter:");
8758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8759                }
8760                if (!intent.debugCheck()) {
8761                    Log.w(TAG, "==> For Activity " + a.info.name);
8762                }
8763                addFilter(intent);
8764            }
8765        }
8766
8767        public final void removeActivity(PackageParser.Activity a, String type) {
8768            mActivities.remove(a.getComponentName());
8769            if (DEBUG_SHOW_INFO) {
8770                Log.v(TAG, "  " + type + " "
8771                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8772                                : a.info.name) + ":");
8773                Log.v(TAG, "    Class=" + a.info.name);
8774            }
8775            final int NI = a.intents.size();
8776            for (int j=0; j<NI; j++) {
8777                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8778                if (DEBUG_SHOW_INFO) {
8779                    Log.v(TAG, "    IntentFilter:");
8780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8781                }
8782                removeFilter(intent);
8783            }
8784        }
8785
8786        @Override
8787        protected boolean allowFilterResult(
8788                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8789            ActivityInfo filterAi = filter.activity.info;
8790            for (int i=dest.size()-1; i>=0; i--) {
8791                ActivityInfo destAi = dest.get(i).activityInfo;
8792                if (destAi.name == filterAi.name
8793                        && destAi.packageName == filterAi.packageName) {
8794                    return false;
8795                }
8796            }
8797            return true;
8798        }
8799
8800        @Override
8801        protected ActivityIntentInfo[] newArray(int size) {
8802            return new ActivityIntentInfo[size];
8803        }
8804
8805        @Override
8806        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8807            if (!sUserManager.exists(userId)) return true;
8808            PackageParser.Package p = filter.activity.owner;
8809            if (p != null) {
8810                PackageSetting ps = (PackageSetting)p.mExtras;
8811                if (ps != null) {
8812                    // System apps are never considered stopped for purposes of
8813                    // filtering, because there may be no way for the user to
8814                    // actually re-launch them.
8815                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8816                            && ps.getStopped(userId);
8817                }
8818            }
8819            return false;
8820        }
8821
8822        @Override
8823        protected boolean isPackageForFilter(String packageName,
8824                PackageParser.ActivityIntentInfo info) {
8825            return packageName.equals(info.activity.owner.packageName);
8826        }
8827
8828        @Override
8829        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8830                int match, int userId) {
8831            if (!sUserManager.exists(userId)) return null;
8832            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8833                return null;
8834            }
8835            final PackageParser.Activity activity = info.activity;
8836            if (mSafeMode && (activity.info.applicationInfo.flags
8837                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8838                return null;
8839            }
8840            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8841            if (ps == null) {
8842                return null;
8843            }
8844            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8845                    ps.readUserState(userId), userId);
8846            if (ai == null) {
8847                return null;
8848            }
8849            final ResolveInfo res = new ResolveInfo();
8850            res.activityInfo = ai;
8851            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8852                res.filter = info;
8853            }
8854            if (info != null) {
8855                res.handleAllWebDataURI = info.handleAllWebDataURI();
8856            }
8857            res.priority = info.getPriority();
8858            res.preferredOrder = activity.owner.mPreferredOrder;
8859            //System.out.println("Result: " + res.activityInfo.className +
8860            //                   " = " + res.priority);
8861            res.match = match;
8862            res.isDefault = info.hasDefault;
8863            res.labelRes = info.labelRes;
8864            res.nonLocalizedLabel = info.nonLocalizedLabel;
8865            if (userNeedsBadging(userId)) {
8866                res.noResourceId = true;
8867            } else {
8868                res.icon = info.icon;
8869            }
8870            res.iconResourceId = info.icon;
8871            res.system = res.activityInfo.applicationInfo.isSystemApp();
8872            return res;
8873        }
8874
8875        @Override
8876        protected void sortResults(List<ResolveInfo> results) {
8877            Collections.sort(results, mResolvePrioritySorter);
8878        }
8879
8880        @Override
8881        protected void dumpFilter(PrintWriter out, String prefix,
8882                PackageParser.ActivityIntentInfo filter) {
8883            out.print(prefix); out.print(
8884                    Integer.toHexString(System.identityHashCode(filter.activity)));
8885                    out.print(' ');
8886                    filter.activity.printComponentShortName(out);
8887                    out.print(" filter ");
8888                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8889        }
8890
8891        @Override
8892        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8893            return filter.activity;
8894        }
8895
8896        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8897            PackageParser.Activity activity = (PackageParser.Activity)label;
8898            out.print(prefix); out.print(
8899                    Integer.toHexString(System.identityHashCode(activity)));
8900                    out.print(' ');
8901                    activity.printComponentShortName(out);
8902            if (count > 1) {
8903                out.print(" ("); out.print(count); out.print(" filters)");
8904            }
8905            out.println();
8906        }
8907
8908//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8909//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8910//            final List<ResolveInfo> retList = Lists.newArrayList();
8911//            while (i.hasNext()) {
8912//                final ResolveInfo resolveInfo = i.next();
8913//                if (isEnabledLP(resolveInfo.activityInfo)) {
8914//                    retList.add(resolveInfo);
8915//                }
8916//            }
8917//            return retList;
8918//        }
8919
8920        // Keys are String (activity class name), values are Activity.
8921        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8922                = new ArrayMap<ComponentName, PackageParser.Activity>();
8923        private int mFlags;
8924    }
8925
8926    private final class ServiceIntentResolver
8927            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8929                boolean defaultOnly, int userId) {
8930            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8931            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8932        }
8933
8934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8935                int userId) {
8936            if (!sUserManager.exists(userId)) return null;
8937            mFlags = flags;
8938            return super.queryIntent(intent, resolvedType,
8939                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8940        }
8941
8942        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8943                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8944            if (!sUserManager.exists(userId)) return null;
8945            if (packageServices == null) {
8946                return null;
8947            }
8948            mFlags = flags;
8949            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8950            final int N = packageServices.size();
8951            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8952                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8953
8954            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8955            for (int i = 0; i < N; ++i) {
8956                intentFilters = packageServices.get(i).intents;
8957                if (intentFilters != null && intentFilters.size() > 0) {
8958                    PackageParser.ServiceIntentInfo[] array =
8959                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8960                    intentFilters.toArray(array);
8961                    listCut.add(array);
8962                }
8963            }
8964            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8965        }
8966
8967        public final void addService(PackageParser.Service s) {
8968            mServices.put(s.getComponentName(), s);
8969            if (DEBUG_SHOW_INFO) {
8970                Log.v(TAG, "  "
8971                        + (s.info.nonLocalizedLabel != null
8972                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8973                Log.v(TAG, "    Class=" + s.info.name);
8974            }
8975            final int NI = s.intents.size();
8976            int j;
8977            for (j=0; j<NI; j++) {
8978                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8979                if (DEBUG_SHOW_INFO) {
8980                    Log.v(TAG, "    IntentFilter:");
8981                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8982                }
8983                if (!intent.debugCheck()) {
8984                    Log.w(TAG, "==> For Service " + s.info.name);
8985                }
8986                addFilter(intent);
8987            }
8988        }
8989
8990        public final void removeService(PackageParser.Service s) {
8991            mServices.remove(s.getComponentName());
8992            if (DEBUG_SHOW_INFO) {
8993                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8994                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8995                Log.v(TAG, "    Class=" + s.info.name);
8996            }
8997            final int NI = s.intents.size();
8998            int j;
8999            for (j=0; j<NI; j++) {
9000                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9001                if (DEBUG_SHOW_INFO) {
9002                    Log.v(TAG, "    IntentFilter:");
9003                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9004                }
9005                removeFilter(intent);
9006            }
9007        }
9008
9009        @Override
9010        protected boolean allowFilterResult(
9011                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9012            ServiceInfo filterSi = filter.service.info;
9013            for (int i=dest.size()-1; i>=0; i--) {
9014                ServiceInfo destAi = dest.get(i).serviceInfo;
9015                if (destAi.name == filterSi.name
9016                        && destAi.packageName == filterSi.packageName) {
9017                    return false;
9018                }
9019            }
9020            return true;
9021        }
9022
9023        @Override
9024        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9025            return new PackageParser.ServiceIntentInfo[size];
9026        }
9027
9028        @Override
9029        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9030            if (!sUserManager.exists(userId)) return true;
9031            PackageParser.Package p = filter.service.owner;
9032            if (p != null) {
9033                PackageSetting ps = (PackageSetting)p.mExtras;
9034                if (ps != null) {
9035                    // System apps are never considered stopped for purposes of
9036                    // filtering, because there may be no way for the user to
9037                    // actually re-launch them.
9038                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9039                            && ps.getStopped(userId);
9040                }
9041            }
9042            return false;
9043        }
9044
9045        @Override
9046        protected boolean isPackageForFilter(String packageName,
9047                PackageParser.ServiceIntentInfo info) {
9048            return packageName.equals(info.service.owner.packageName);
9049        }
9050
9051        @Override
9052        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9053                int match, int userId) {
9054            if (!sUserManager.exists(userId)) return null;
9055            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9056            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9057                return null;
9058            }
9059            final PackageParser.Service service = info.service;
9060            if (mSafeMode && (service.info.applicationInfo.flags
9061                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9062                return null;
9063            }
9064            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9065            if (ps == null) {
9066                return null;
9067            }
9068            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9069                    ps.readUserState(userId), userId);
9070            if (si == null) {
9071                return null;
9072            }
9073            final ResolveInfo res = new ResolveInfo();
9074            res.serviceInfo = si;
9075            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9076                res.filter = filter;
9077            }
9078            res.priority = info.getPriority();
9079            res.preferredOrder = service.owner.mPreferredOrder;
9080            res.match = match;
9081            res.isDefault = info.hasDefault;
9082            res.labelRes = info.labelRes;
9083            res.nonLocalizedLabel = info.nonLocalizedLabel;
9084            res.icon = info.icon;
9085            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9086            return res;
9087        }
9088
9089        @Override
9090        protected void sortResults(List<ResolveInfo> results) {
9091            Collections.sort(results, mResolvePrioritySorter);
9092        }
9093
9094        @Override
9095        protected void dumpFilter(PrintWriter out, String prefix,
9096                PackageParser.ServiceIntentInfo filter) {
9097            out.print(prefix); out.print(
9098                    Integer.toHexString(System.identityHashCode(filter.service)));
9099                    out.print(' ');
9100                    filter.service.printComponentShortName(out);
9101                    out.print(" filter ");
9102                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9103        }
9104
9105        @Override
9106        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9107            return filter.service;
9108        }
9109
9110        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9111            PackageParser.Service service = (PackageParser.Service)label;
9112            out.print(prefix); out.print(
9113                    Integer.toHexString(System.identityHashCode(service)));
9114                    out.print(' ');
9115                    service.printComponentShortName(out);
9116            if (count > 1) {
9117                out.print(" ("); out.print(count); out.print(" filters)");
9118            }
9119            out.println();
9120        }
9121
9122//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9123//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9124//            final List<ResolveInfo> retList = Lists.newArrayList();
9125//            while (i.hasNext()) {
9126//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9127//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9128//                    retList.add(resolveInfo);
9129//                }
9130//            }
9131//            return retList;
9132//        }
9133
9134        // Keys are String (activity class name), values are Activity.
9135        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9136                = new ArrayMap<ComponentName, PackageParser.Service>();
9137        private int mFlags;
9138    };
9139
9140    private final class ProviderIntentResolver
9141            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9142        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9143                boolean defaultOnly, int userId) {
9144            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9145            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9146        }
9147
9148        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9149                int userId) {
9150            if (!sUserManager.exists(userId))
9151                return null;
9152            mFlags = flags;
9153            return super.queryIntent(intent, resolvedType,
9154                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9155        }
9156
9157        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9158                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9159            if (!sUserManager.exists(userId))
9160                return null;
9161            if (packageProviders == null) {
9162                return null;
9163            }
9164            mFlags = flags;
9165            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9166            final int N = packageProviders.size();
9167            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9168                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9169
9170            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9171            for (int i = 0; i < N; ++i) {
9172                intentFilters = packageProviders.get(i).intents;
9173                if (intentFilters != null && intentFilters.size() > 0) {
9174                    PackageParser.ProviderIntentInfo[] array =
9175                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9176                    intentFilters.toArray(array);
9177                    listCut.add(array);
9178                }
9179            }
9180            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9181        }
9182
9183        public final void addProvider(PackageParser.Provider p) {
9184            if (mProviders.containsKey(p.getComponentName())) {
9185                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9186                return;
9187            }
9188
9189            mProviders.put(p.getComponentName(), p);
9190            if (DEBUG_SHOW_INFO) {
9191                Log.v(TAG, "  "
9192                        + (p.info.nonLocalizedLabel != null
9193                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9194                Log.v(TAG, "    Class=" + p.info.name);
9195            }
9196            final int NI = p.intents.size();
9197            int j;
9198            for (j = 0; j < NI; j++) {
9199                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9200                if (DEBUG_SHOW_INFO) {
9201                    Log.v(TAG, "    IntentFilter:");
9202                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9203                }
9204                if (!intent.debugCheck()) {
9205                    Log.w(TAG, "==> For Provider " + p.info.name);
9206                }
9207                addFilter(intent);
9208            }
9209        }
9210
9211        public final void removeProvider(PackageParser.Provider p) {
9212            mProviders.remove(p.getComponentName());
9213            if (DEBUG_SHOW_INFO) {
9214                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9215                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9216                Log.v(TAG, "    Class=" + p.info.name);
9217            }
9218            final int NI = p.intents.size();
9219            int j;
9220            for (j = 0; j < NI; j++) {
9221                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9222                if (DEBUG_SHOW_INFO) {
9223                    Log.v(TAG, "    IntentFilter:");
9224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9225                }
9226                removeFilter(intent);
9227            }
9228        }
9229
9230        @Override
9231        protected boolean allowFilterResult(
9232                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9233            ProviderInfo filterPi = filter.provider.info;
9234            for (int i = dest.size() - 1; i >= 0; i--) {
9235                ProviderInfo destPi = dest.get(i).providerInfo;
9236                if (destPi.name == filterPi.name
9237                        && destPi.packageName == filterPi.packageName) {
9238                    return false;
9239                }
9240            }
9241            return true;
9242        }
9243
9244        @Override
9245        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9246            return new PackageParser.ProviderIntentInfo[size];
9247        }
9248
9249        @Override
9250        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9251            if (!sUserManager.exists(userId))
9252                return true;
9253            PackageParser.Package p = filter.provider.owner;
9254            if (p != null) {
9255                PackageSetting ps = (PackageSetting) p.mExtras;
9256                if (ps != null) {
9257                    // System apps are never considered stopped for purposes of
9258                    // filtering, because there may be no way for the user to
9259                    // actually re-launch them.
9260                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9261                            && ps.getStopped(userId);
9262                }
9263            }
9264            return false;
9265        }
9266
9267        @Override
9268        protected boolean isPackageForFilter(String packageName,
9269                PackageParser.ProviderIntentInfo info) {
9270            return packageName.equals(info.provider.owner.packageName);
9271        }
9272
9273        @Override
9274        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9275                int match, int userId) {
9276            if (!sUserManager.exists(userId))
9277                return null;
9278            final PackageParser.ProviderIntentInfo info = filter;
9279            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9280                return null;
9281            }
9282            final PackageParser.Provider provider = info.provider;
9283            if (mSafeMode && (provider.info.applicationInfo.flags
9284                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9285                return null;
9286            }
9287            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9288            if (ps == null) {
9289                return null;
9290            }
9291            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9292                    ps.readUserState(userId), userId);
9293            if (pi == null) {
9294                return null;
9295            }
9296            final ResolveInfo res = new ResolveInfo();
9297            res.providerInfo = pi;
9298            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9299                res.filter = filter;
9300            }
9301            res.priority = info.getPriority();
9302            res.preferredOrder = provider.owner.mPreferredOrder;
9303            res.match = match;
9304            res.isDefault = info.hasDefault;
9305            res.labelRes = info.labelRes;
9306            res.nonLocalizedLabel = info.nonLocalizedLabel;
9307            res.icon = info.icon;
9308            res.system = res.providerInfo.applicationInfo.isSystemApp();
9309            return res;
9310        }
9311
9312        @Override
9313        protected void sortResults(List<ResolveInfo> results) {
9314            Collections.sort(results, mResolvePrioritySorter);
9315        }
9316
9317        @Override
9318        protected void dumpFilter(PrintWriter out, String prefix,
9319                PackageParser.ProviderIntentInfo filter) {
9320            out.print(prefix);
9321            out.print(
9322                    Integer.toHexString(System.identityHashCode(filter.provider)));
9323            out.print(' ');
9324            filter.provider.printComponentShortName(out);
9325            out.print(" filter ");
9326            out.println(Integer.toHexString(System.identityHashCode(filter)));
9327        }
9328
9329        @Override
9330        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9331            return filter.provider;
9332        }
9333
9334        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9335            PackageParser.Provider provider = (PackageParser.Provider)label;
9336            out.print(prefix); out.print(
9337                    Integer.toHexString(System.identityHashCode(provider)));
9338                    out.print(' ');
9339                    provider.printComponentShortName(out);
9340            if (count > 1) {
9341                out.print(" ("); out.print(count); out.print(" filters)");
9342            }
9343            out.println();
9344        }
9345
9346        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9347                = new ArrayMap<ComponentName, PackageParser.Provider>();
9348        private int mFlags;
9349    };
9350
9351    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9352            new Comparator<ResolveInfo>() {
9353        public int compare(ResolveInfo r1, ResolveInfo r2) {
9354            int v1 = r1.priority;
9355            int v2 = r2.priority;
9356            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9357            if (v1 != v2) {
9358                return (v1 > v2) ? -1 : 1;
9359            }
9360            v1 = r1.preferredOrder;
9361            v2 = r2.preferredOrder;
9362            if (v1 != v2) {
9363                return (v1 > v2) ? -1 : 1;
9364            }
9365            if (r1.isDefault != r2.isDefault) {
9366                return r1.isDefault ? -1 : 1;
9367            }
9368            v1 = r1.match;
9369            v2 = r2.match;
9370            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9371            if (v1 != v2) {
9372                return (v1 > v2) ? -1 : 1;
9373            }
9374            if (r1.system != r2.system) {
9375                return r1.system ? -1 : 1;
9376            }
9377            return 0;
9378        }
9379    };
9380
9381    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9382            new Comparator<ProviderInfo>() {
9383        public int compare(ProviderInfo p1, ProviderInfo p2) {
9384            final int v1 = p1.initOrder;
9385            final int v2 = p2.initOrder;
9386            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9387        }
9388    };
9389
9390    final void sendPackageBroadcast(final String action, final String pkg,
9391            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9392            final int[] userIds) {
9393        mHandler.post(new Runnable() {
9394            @Override
9395            public void run() {
9396                try {
9397                    final IActivityManager am = ActivityManagerNative.getDefault();
9398                    if (am == null) return;
9399                    final int[] resolvedUserIds;
9400                    if (userIds == null) {
9401                        resolvedUserIds = am.getRunningUserIds();
9402                    } else {
9403                        resolvedUserIds = userIds;
9404                    }
9405                    for (int id : resolvedUserIds) {
9406                        final Intent intent = new Intent(action,
9407                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9408                        if (extras != null) {
9409                            intent.putExtras(extras);
9410                        }
9411                        if (targetPkg != null) {
9412                            intent.setPackage(targetPkg);
9413                        }
9414                        // Modify the UID when posting to other users
9415                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9416                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9417                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9418                            intent.putExtra(Intent.EXTRA_UID, uid);
9419                        }
9420                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9421                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9422                        if (DEBUG_BROADCASTS) {
9423                            RuntimeException here = new RuntimeException("here");
9424                            here.fillInStackTrace();
9425                            Slog.d(TAG, "Sending to user " + id + ": "
9426                                    + intent.toShortString(false, true, false, false)
9427                                    + " " + intent.getExtras(), here);
9428                        }
9429                        am.broadcastIntent(null, intent, null, finishedReceiver,
9430                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9431                                null, finishedReceiver != null, false, id);
9432                    }
9433                } catch (RemoteException ex) {
9434                }
9435            }
9436        });
9437    }
9438
9439    /**
9440     * Check if the external storage media is available. This is true if there
9441     * is a mounted external storage medium or if the external storage is
9442     * emulated.
9443     */
9444    private boolean isExternalMediaAvailable() {
9445        return mMediaMounted || Environment.isExternalStorageEmulated();
9446    }
9447
9448    @Override
9449    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9450        // writer
9451        synchronized (mPackages) {
9452            if (!isExternalMediaAvailable()) {
9453                // If the external storage is no longer mounted at this point,
9454                // the caller may not have been able to delete all of this
9455                // packages files and can not delete any more.  Bail.
9456                return null;
9457            }
9458            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9459            if (lastPackage != null) {
9460                pkgs.remove(lastPackage);
9461            }
9462            if (pkgs.size() > 0) {
9463                return pkgs.get(0);
9464            }
9465        }
9466        return null;
9467    }
9468
9469    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9470        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9471                userId, andCode ? 1 : 0, packageName);
9472        if (mSystemReady) {
9473            msg.sendToTarget();
9474        } else {
9475            if (mPostSystemReadyMessages == null) {
9476                mPostSystemReadyMessages = new ArrayList<>();
9477            }
9478            mPostSystemReadyMessages.add(msg);
9479        }
9480    }
9481
9482    void startCleaningPackages() {
9483        // reader
9484        synchronized (mPackages) {
9485            if (!isExternalMediaAvailable()) {
9486                return;
9487            }
9488            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9489                return;
9490            }
9491        }
9492        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9493        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9494        IActivityManager am = ActivityManagerNative.getDefault();
9495        if (am != null) {
9496            try {
9497                am.startService(null, intent, null, mContext.getOpPackageName(),
9498                        UserHandle.USER_OWNER);
9499            } catch (RemoteException e) {
9500            }
9501        }
9502    }
9503
9504    @Override
9505    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9506            int installFlags, String installerPackageName, VerificationParams verificationParams,
9507            String packageAbiOverride) {
9508        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9509                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9510    }
9511
9512    @Override
9513    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9514            int installFlags, String installerPackageName, VerificationParams verificationParams,
9515            String packageAbiOverride, int userId) {
9516        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9517
9518        final int callingUid = Binder.getCallingUid();
9519        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9520
9521        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9522            try {
9523                if (observer != null) {
9524                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9525                }
9526            } catch (RemoteException re) {
9527            }
9528            return;
9529        }
9530
9531        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9532            installFlags |= PackageManager.INSTALL_FROM_ADB;
9533
9534        } else {
9535            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9536            // about installerPackageName.
9537
9538            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9539            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9540        }
9541
9542        UserHandle user;
9543        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9544            user = UserHandle.ALL;
9545        } else {
9546            user = new UserHandle(userId);
9547        }
9548
9549        // Only system components can circumvent runtime permissions when installing.
9550        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9551                && mContext.checkCallingOrSelfPermission(Manifest.permission
9552                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9553            throw new SecurityException("You need the "
9554                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9555                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9556        }
9557
9558        verificationParams.setInstallerUid(callingUid);
9559
9560        final File originFile = new File(originPath);
9561        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9562
9563        final Message msg = mHandler.obtainMessage(INIT_COPY);
9564        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9565                null, verificationParams, user, packageAbiOverride, null);
9566        mHandler.sendMessage(msg);
9567    }
9568
9569    void installStage(String packageName, File stagedDir, String stagedCid,
9570            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9571            String installerPackageName, int installerUid, UserHandle user) {
9572        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9573                params.referrerUri, installerUid, null);
9574        verifParams.setInstallerUid(installerUid);
9575
9576        final OriginInfo origin;
9577        if (stagedDir != null) {
9578            origin = OriginInfo.fromStagedFile(stagedDir);
9579        } else {
9580            origin = OriginInfo.fromStagedContainer(stagedCid);
9581        }
9582
9583        final Message msg = mHandler.obtainMessage(INIT_COPY);
9584        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9585                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9586                params.grantedRuntimePermissions);
9587        mHandler.sendMessage(msg);
9588    }
9589
9590    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9591        Bundle extras = new Bundle(1);
9592        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9593
9594        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9595                packageName, extras, null, null, new int[] {userId});
9596        try {
9597            IActivityManager am = ActivityManagerNative.getDefault();
9598            final boolean isSystem =
9599                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9600            if (isSystem && am.isUserRunning(userId, false)) {
9601                // The just-installed/enabled app is bundled on the system, so presumed
9602                // to be able to run automatically without needing an explicit launch.
9603                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9604                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9605                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9606                        .setPackage(packageName);
9607                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9608                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9609            }
9610        } catch (RemoteException e) {
9611            // shouldn't happen
9612            Slog.w(TAG, "Unable to bootstrap installed package", e);
9613        }
9614    }
9615
9616    @Override
9617    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9618            int userId) {
9619        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9620        PackageSetting pkgSetting;
9621        final int uid = Binder.getCallingUid();
9622        enforceCrossUserPermission(uid, userId, true, true,
9623                "setApplicationHiddenSetting for user " + userId);
9624
9625        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9626            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9627            return false;
9628        }
9629
9630        long callingId = Binder.clearCallingIdentity();
9631        try {
9632            boolean sendAdded = false;
9633            boolean sendRemoved = false;
9634            // writer
9635            synchronized (mPackages) {
9636                pkgSetting = mSettings.mPackages.get(packageName);
9637                if (pkgSetting == null) {
9638                    return false;
9639                }
9640                if (pkgSetting.getHidden(userId) != hidden) {
9641                    pkgSetting.setHidden(hidden, userId);
9642                    mSettings.writePackageRestrictionsLPr(userId);
9643                    if (hidden) {
9644                        sendRemoved = true;
9645                    } else {
9646                        sendAdded = true;
9647                    }
9648                }
9649            }
9650            if (sendAdded) {
9651                sendPackageAddedForUser(packageName, pkgSetting, userId);
9652                return true;
9653            }
9654            if (sendRemoved) {
9655                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9656                        "hiding pkg");
9657                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9658                return true;
9659            }
9660        } finally {
9661            Binder.restoreCallingIdentity(callingId);
9662        }
9663        return false;
9664    }
9665
9666    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9667            int userId) {
9668        final PackageRemovedInfo info = new PackageRemovedInfo();
9669        info.removedPackage = packageName;
9670        info.removedUsers = new int[] {userId};
9671        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9672        info.sendBroadcast(false, false, false);
9673    }
9674
9675    /**
9676     * Returns true if application is not found or there was an error. Otherwise it returns
9677     * the hidden state of the package for the given user.
9678     */
9679    @Override
9680    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9682        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9683                false, "getApplicationHidden for user " + userId);
9684        PackageSetting pkgSetting;
9685        long callingId = Binder.clearCallingIdentity();
9686        try {
9687            // writer
9688            synchronized (mPackages) {
9689                pkgSetting = mSettings.mPackages.get(packageName);
9690                if (pkgSetting == null) {
9691                    return true;
9692                }
9693                return pkgSetting.getHidden(userId);
9694            }
9695        } finally {
9696            Binder.restoreCallingIdentity(callingId);
9697        }
9698    }
9699
9700    /**
9701     * @hide
9702     */
9703    @Override
9704    public int installExistingPackageAsUser(String packageName, int userId) {
9705        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9706                null);
9707        PackageSetting pkgSetting;
9708        final int uid = Binder.getCallingUid();
9709        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9710                + userId);
9711        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9712            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9713        }
9714
9715        long callingId = Binder.clearCallingIdentity();
9716        try {
9717            boolean sendAdded = false;
9718
9719            // writer
9720            synchronized (mPackages) {
9721                pkgSetting = mSettings.mPackages.get(packageName);
9722                if (pkgSetting == null) {
9723                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9724                }
9725                if (!pkgSetting.getInstalled(userId)) {
9726                    pkgSetting.setInstalled(true, userId);
9727                    pkgSetting.setHidden(false, userId);
9728                    mSettings.writePackageRestrictionsLPr(userId);
9729                    sendAdded = true;
9730                }
9731            }
9732
9733            if (sendAdded) {
9734                sendPackageAddedForUser(packageName, pkgSetting, userId);
9735            }
9736        } finally {
9737            Binder.restoreCallingIdentity(callingId);
9738        }
9739
9740        return PackageManager.INSTALL_SUCCEEDED;
9741    }
9742
9743    boolean isUserRestricted(int userId, String restrictionKey) {
9744        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9745        if (restrictions.getBoolean(restrictionKey, false)) {
9746            Log.w(TAG, "User is restricted: " + restrictionKey);
9747            return true;
9748        }
9749        return false;
9750    }
9751
9752    @Override
9753    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9754        mContext.enforceCallingOrSelfPermission(
9755                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9756                "Only package verification agents can verify applications");
9757
9758        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9759        final PackageVerificationResponse response = new PackageVerificationResponse(
9760                verificationCode, Binder.getCallingUid());
9761        msg.arg1 = id;
9762        msg.obj = response;
9763        mHandler.sendMessage(msg);
9764    }
9765
9766    @Override
9767    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9768            long millisecondsToDelay) {
9769        mContext.enforceCallingOrSelfPermission(
9770                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9771                "Only package verification agents can extend verification timeouts");
9772
9773        final PackageVerificationState state = mPendingVerification.get(id);
9774        final PackageVerificationResponse response = new PackageVerificationResponse(
9775                verificationCodeAtTimeout, Binder.getCallingUid());
9776
9777        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9778            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9779        }
9780        if (millisecondsToDelay < 0) {
9781            millisecondsToDelay = 0;
9782        }
9783        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9784                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9785            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9786        }
9787
9788        if ((state != null) && !state.timeoutExtended()) {
9789            state.extendTimeout();
9790
9791            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9792            msg.arg1 = id;
9793            msg.obj = response;
9794            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9795        }
9796    }
9797
9798    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9799            int verificationCode, UserHandle user) {
9800        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9801        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9802        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9803        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9804        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9805
9806        mContext.sendBroadcastAsUser(intent, user,
9807                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9808    }
9809
9810    private ComponentName matchComponentForVerifier(String packageName,
9811            List<ResolveInfo> receivers) {
9812        ActivityInfo targetReceiver = null;
9813
9814        final int NR = receivers.size();
9815        for (int i = 0; i < NR; i++) {
9816            final ResolveInfo info = receivers.get(i);
9817            if (info.activityInfo == null) {
9818                continue;
9819            }
9820
9821            if (packageName.equals(info.activityInfo.packageName)) {
9822                targetReceiver = info.activityInfo;
9823                break;
9824            }
9825        }
9826
9827        if (targetReceiver == null) {
9828            return null;
9829        }
9830
9831        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9832    }
9833
9834    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9835            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9836        if (pkgInfo.verifiers.length == 0) {
9837            return null;
9838        }
9839
9840        final int N = pkgInfo.verifiers.length;
9841        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9842        for (int i = 0; i < N; i++) {
9843            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9844
9845            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9846                    receivers);
9847            if (comp == null) {
9848                continue;
9849            }
9850
9851            final int verifierUid = getUidForVerifier(verifierInfo);
9852            if (verifierUid == -1) {
9853                continue;
9854            }
9855
9856            if (DEBUG_VERIFY) {
9857                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9858                        + " with the correct signature");
9859            }
9860            sufficientVerifiers.add(comp);
9861            verificationState.addSufficientVerifier(verifierUid);
9862        }
9863
9864        return sufficientVerifiers;
9865    }
9866
9867    private int getUidForVerifier(VerifierInfo verifierInfo) {
9868        synchronized (mPackages) {
9869            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9870            if (pkg == null) {
9871                return -1;
9872            } else if (pkg.mSignatures.length != 1) {
9873                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9874                        + " has more than one signature; ignoring");
9875                return -1;
9876            }
9877
9878            /*
9879             * If the public key of the package's signature does not match
9880             * our expected public key, then this is a different package and
9881             * we should skip.
9882             */
9883
9884            final byte[] expectedPublicKey;
9885            try {
9886                final Signature verifierSig = pkg.mSignatures[0];
9887                final PublicKey publicKey = verifierSig.getPublicKey();
9888                expectedPublicKey = publicKey.getEncoded();
9889            } catch (CertificateException e) {
9890                return -1;
9891            }
9892
9893            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9894
9895            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9896                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9897                        + " does not have the expected public key; ignoring");
9898                return -1;
9899            }
9900
9901            return pkg.applicationInfo.uid;
9902        }
9903    }
9904
9905    @Override
9906    public void finishPackageInstall(int token) {
9907        enforceSystemOrRoot("Only the system is allowed to finish installs");
9908
9909        if (DEBUG_INSTALL) {
9910            Slog.v(TAG, "BM finishing package install for " + token);
9911        }
9912
9913        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9914        mHandler.sendMessage(msg);
9915    }
9916
9917    /**
9918     * Get the verification agent timeout.
9919     *
9920     * @return verification timeout in milliseconds
9921     */
9922    private long getVerificationTimeout() {
9923        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9924                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9925                DEFAULT_VERIFICATION_TIMEOUT);
9926    }
9927
9928    /**
9929     * Get the default verification agent response code.
9930     *
9931     * @return default verification response code
9932     */
9933    private int getDefaultVerificationResponse() {
9934        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9935                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9936                DEFAULT_VERIFICATION_RESPONSE);
9937    }
9938
9939    /**
9940     * Check whether or not package verification has been enabled.
9941     *
9942     * @return true if verification should be performed
9943     */
9944    private boolean isVerificationEnabled(int userId, int installFlags) {
9945        if (!DEFAULT_VERIFY_ENABLE) {
9946            return false;
9947        }
9948
9949        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9950
9951        // Check if installing from ADB
9952        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9953            // Do not run verification in a test harness environment
9954            if (ActivityManager.isRunningInTestHarness()) {
9955                return false;
9956            }
9957            if (ensureVerifyAppsEnabled) {
9958                return true;
9959            }
9960            // Check if the developer does not want package verification for ADB installs
9961            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9962                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9963                return false;
9964            }
9965        }
9966
9967        if (ensureVerifyAppsEnabled) {
9968            return true;
9969        }
9970
9971        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9972                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9973    }
9974
9975    @Override
9976    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9977            throws RemoteException {
9978        mContext.enforceCallingOrSelfPermission(
9979                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9980                "Only intentfilter verification agents can verify applications");
9981
9982        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9983        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9984                Binder.getCallingUid(), verificationCode, failedDomains);
9985        msg.arg1 = id;
9986        msg.obj = response;
9987        mHandler.sendMessage(msg);
9988    }
9989
9990    @Override
9991    public int getIntentVerificationStatus(String packageName, int userId) {
9992        synchronized (mPackages) {
9993            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9994        }
9995    }
9996
9997    @Override
9998    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9999        mContext.enforceCallingOrSelfPermission(
10000                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10001
10002        boolean result = false;
10003        synchronized (mPackages) {
10004            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10005        }
10006        if (result) {
10007            scheduleWritePackageRestrictionsLocked(userId);
10008        }
10009        return result;
10010    }
10011
10012    @Override
10013    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10014        synchronized (mPackages) {
10015            return mSettings.getIntentFilterVerificationsLPr(packageName);
10016        }
10017    }
10018
10019    @Override
10020    public List<IntentFilter> getAllIntentFilters(String packageName) {
10021        if (TextUtils.isEmpty(packageName)) {
10022            return Collections.<IntentFilter>emptyList();
10023        }
10024        synchronized (mPackages) {
10025            PackageParser.Package pkg = mPackages.get(packageName);
10026            if (pkg == null || pkg.activities == null) {
10027                return Collections.<IntentFilter>emptyList();
10028            }
10029            final int count = pkg.activities.size();
10030            ArrayList<IntentFilter> result = new ArrayList<>();
10031            for (int n=0; n<count; n++) {
10032                PackageParser.Activity activity = pkg.activities.get(n);
10033                if (activity.intents != null || activity.intents.size() > 0) {
10034                    result.addAll(activity.intents);
10035                }
10036            }
10037            return result;
10038        }
10039    }
10040
10041    @Override
10042    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10043        mContext.enforceCallingOrSelfPermission(
10044                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10045
10046        synchronized (mPackages) {
10047            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10048            if (packageName != null) {
10049                result |= updateIntentVerificationStatus(packageName,
10050                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10051                        userId);
10052                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10053                        packageName, userId);
10054            }
10055            return result;
10056        }
10057    }
10058
10059    @Override
10060    public String getDefaultBrowserPackageName(int userId) {
10061        synchronized (mPackages) {
10062            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10063        }
10064    }
10065
10066    /**
10067     * Get the "allow unknown sources" setting.
10068     *
10069     * @return the current "allow unknown sources" setting
10070     */
10071    private int getUnknownSourcesSettings() {
10072        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10073                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10074                -1);
10075    }
10076
10077    @Override
10078    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10079        final int uid = Binder.getCallingUid();
10080        // writer
10081        synchronized (mPackages) {
10082            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10083            if (targetPackageSetting == null) {
10084                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10085            }
10086
10087            PackageSetting installerPackageSetting;
10088            if (installerPackageName != null) {
10089                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10090                if (installerPackageSetting == null) {
10091                    throw new IllegalArgumentException("Unknown installer package: "
10092                            + installerPackageName);
10093                }
10094            } else {
10095                installerPackageSetting = null;
10096            }
10097
10098            Signature[] callerSignature;
10099            Object obj = mSettings.getUserIdLPr(uid);
10100            if (obj != null) {
10101                if (obj instanceof SharedUserSetting) {
10102                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10103                } else if (obj instanceof PackageSetting) {
10104                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10105                } else {
10106                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10107                }
10108            } else {
10109                throw new SecurityException("Unknown calling uid " + uid);
10110            }
10111
10112            // Verify: can't set installerPackageName to a package that is
10113            // not signed with the same cert as the caller.
10114            if (installerPackageSetting != null) {
10115                if (compareSignatures(callerSignature,
10116                        installerPackageSetting.signatures.mSignatures)
10117                        != PackageManager.SIGNATURE_MATCH) {
10118                    throw new SecurityException(
10119                            "Caller does not have same cert as new installer package "
10120                            + installerPackageName);
10121                }
10122            }
10123
10124            // Verify: if target already has an installer package, it must
10125            // be signed with the same cert as the caller.
10126            if (targetPackageSetting.installerPackageName != null) {
10127                PackageSetting setting = mSettings.mPackages.get(
10128                        targetPackageSetting.installerPackageName);
10129                // If the currently set package isn't valid, then it's always
10130                // okay to change it.
10131                if (setting != null) {
10132                    if (compareSignatures(callerSignature,
10133                            setting.signatures.mSignatures)
10134                            != PackageManager.SIGNATURE_MATCH) {
10135                        throw new SecurityException(
10136                                "Caller does not have same cert as old installer package "
10137                                + targetPackageSetting.installerPackageName);
10138                    }
10139                }
10140            }
10141
10142            // Okay!
10143            targetPackageSetting.installerPackageName = installerPackageName;
10144            scheduleWriteSettingsLocked();
10145        }
10146    }
10147
10148    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10149        // Queue up an async operation since the package installation may take a little while.
10150        mHandler.post(new Runnable() {
10151            public void run() {
10152                mHandler.removeCallbacks(this);
10153                 // Result object to be returned
10154                PackageInstalledInfo res = new PackageInstalledInfo();
10155                res.returnCode = currentStatus;
10156                res.uid = -1;
10157                res.pkg = null;
10158                res.removedInfo = new PackageRemovedInfo();
10159                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10160                    args.doPreInstall(res.returnCode);
10161                    synchronized (mInstallLock) {
10162                        installPackageLI(args, res);
10163                    }
10164                    args.doPostInstall(res.returnCode, res.uid);
10165                }
10166
10167                // A restore should be performed at this point if (a) the install
10168                // succeeded, (b) the operation is not an update, and (c) the new
10169                // package has not opted out of backup participation.
10170                final boolean update = res.removedInfo.removedPackage != null;
10171                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10172                boolean doRestore = !update
10173                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10174
10175                // Set up the post-install work request bookkeeping.  This will be used
10176                // and cleaned up by the post-install event handling regardless of whether
10177                // there's a restore pass performed.  Token values are >= 1.
10178                int token;
10179                if (mNextInstallToken < 0) mNextInstallToken = 1;
10180                token = mNextInstallToken++;
10181
10182                PostInstallData data = new PostInstallData(args, res);
10183                mRunningInstalls.put(token, data);
10184                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10185
10186                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10187                    // Pass responsibility to the Backup Manager.  It will perform a
10188                    // restore if appropriate, then pass responsibility back to the
10189                    // Package Manager to run the post-install observer callbacks
10190                    // and broadcasts.
10191                    IBackupManager bm = IBackupManager.Stub.asInterface(
10192                            ServiceManager.getService(Context.BACKUP_SERVICE));
10193                    if (bm != null) {
10194                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10195                                + " to BM for possible restore");
10196                        try {
10197                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10198                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10199                            } else {
10200                                doRestore = false;
10201                            }
10202                        } catch (RemoteException e) {
10203                            // can't happen; the backup manager is local
10204                        } catch (Exception e) {
10205                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10206                            doRestore = false;
10207                        }
10208                    } else {
10209                        Slog.e(TAG, "Backup Manager not found!");
10210                        doRestore = false;
10211                    }
10212                }
10213
10214                if (!doRestore) {
10215                    // No restore possible, or the Backup Manager was mysteriously not
10216                    // available -- just fire the post-install work request directly.
10217                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10218                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10219                    mHandler.sendMessage(msg);
10220                }
10221            }
10222        });
10223    }
10224
10225    private abstract class HandlerParams {
10226        private static final int MAX_RETRIES = 4;
10227
10228        /**
10229         * Number of times startCopy() has been attempted and had a non-fatal
10230         * error.
10231         */
10232        private int mRetries = 0;
10233
10234        /** User handle for the user requesting the information or installation. */
10235        private final UserHandle mUser;
10236
10237        HandlerParams(UserHandle user) {
10238            mUser = user;
10239        }
10240
10241        UserHandle getUser() {
10242            return mUser;
10243        }
10244
10245        final boolean startCopy() {
10246            boolean res;
10247            try {
10248                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10249
10250                if (++mRetries > MAX_RETRIES) {
10251                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10252                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10253                    handleServiceError();
10254                    return false;
10255                } else {
10256                    handleStartCopy();
10257                    res = true;
10258                }
10259            } catch (RemoteException e) {
10260                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10261                mHandler.sendEmptyMessage(MCS_RECONNECT);
10262                res = false;
10263            }
10264            handleReturnCode();
10265            return res;
10266        }
10267
10268        final void serviceError() {
10269            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10270            handleServiceError();
10271            handleReturnCode();
10272        }
10273
10274        abstract void handleStartCopy() throws RemoteException;
10275        abstract void handleServiceError();
10276        abstract void handleReturnCode();
10277    }
10278
10279    class MeasureParams extends HandlerParams {
10280        private final PackageStats mStats;
10281        private boolean mSuccess;
10282
10283        private final IPackageStatsObserver mObserver;
10284
10285        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10286            super(new UserHandle(stats.userHandle));
10287            mObserver = observer;
10288            mStats = stats;
10289        }
10290
10291        @Override
10292        public String toString() {
10293            return "MeasureParams{"
10294                + Integer.toHexString(System.identityHashCode(this))
10295                + " " + mStats.packageName + "}";
10296        }
10297
10298        @Override
10299        void handleStartCopy() throws RemoteException {
10300            synchronized (mInstallLock) {
10301                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10302            }
10303
10304            if (mSuccess) {
10305                final boolean mounted;
10306                if (Environment.isExternalStorageEmulated()) {
10307                    mounted = true;
10308                } else {
10309                    final String status = Environment.getExternalStorageState();
10310                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10311                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10312                }
10313
10314                if (mounted) {
10315                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10316
10317                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10318                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10319
10320                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10321                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10322
10323                    // Always subtract cache size, since it's a subdirectory
10324                    mStats.externalDataSize -= mStats.externalCacheSize;
10325
10326                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10327                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10328
10329                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10330                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10331                }
10332            }
10333        }
10334
10335        @Override
10336        void handleReturnCode() {
10337            if (mObserver != null) {
10338                try {
10339                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10340                } catch (RemoteException e) {
10341                    Slog.i(TAG, "Observer no longer exists.");
10342                }
10343            }
10344        }
10345
10346        @Override
10347        void handleServiceError() {
10348            Slog.e(TAG, "Could not measure application " + mStats.packageName
10349                            + " external storage");
10350        }
10351    }
10352
10353    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10354            throws RemoteException {
10355        long result = 0;
10356        for (File path : paths) {
10357            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10358        }
10359        return result;
10360    }
10361
10362    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10363        for (File path : paths) {
10364            try {
10365                mcs.clearDirectory(path.getAbsolutePath());
10366            } catch (RemoteException e) {
10367            }
10368        }
10369    }
10370
10371    static class OriginInfo {
10372        /**
10373         * Location where install is coming from, before it has been
10374         * copied/renamed into place. This could be a single monolithic APK
10375         * file, or a cluster directory. This location may be untrusted.
10376         */
10377        final File file;
10378        final String cid;
10379
10380        /**
10381         * Flag indicating that {@link #file} or {@link #cid} has already been
10382         * staged, meaning downstream users don't need to defensively copy the
10383         * contents.
10384         */
10385        final boolean staged;
10386
10387        /**
10388         * Flag indicating that {@link #file} or {@link #cid} is an already
10389         * installed app that is being moved.
10390         */
10391        final boolean existing;
10392
10393        final String resolvedPath;
10394        final File resolvedFile;
10395
10396        static OriginInfo fromNothing() {
10397            return new OriginInfo(null, null, false, false);
10398        }
10399
10400        static OriginInfo fromUntrustedFile(File file) {
10401            return new OriginInfo(file, null, false, false);
10402        }
10403
10404        static OriginInfo fromExistingFile(File file) {
10405            return new OriginInfo(file, null, false, true);
10406        }
10407
10408        static OriginInfo fromStagedFile(File file) {
10409            return new OriginInfo(file, null, true, false);
10410        }
10411
10412        static OriginInfo fromStagedContainer(String cid) {
10413            return new OriginInfo(null, cid, true, false);
10414        }
10415
10416        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10417            this.file = file;
10418            this.cid = cid;
10419            this.staged = staged;
10420            this.existing = existing;
10421
10422            if (cid != null) {
10423                resolvedPath = PackageHelper.getSdDir(cid);
10424                resolvedFile = new File(resolvedPath);
10425            } else if (file != null) {
10426                resolvedPath = file.getAbsolutePath();
10427                resolvedFile = file;
10428            } else {
10429                resolvedPath = null;
10430                resolvedFile = null;
10431            }
10432        }
10433    }
10434
10435    class MoveInfo {
10436        final int moveId;
10437        final String fromUuid;
10438        final String toUuid;
10439        final String packageName;
10440        final String dataAppName;
10441        final int appId;
10442        final String seinfo;
10443
10444        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10445                String dataAppName, int appId, String seinfo) {
10446            this.moveId = moveId;
10447            this.fromUuid = fromUuid;
10448            this.toUuid = toUuid;
10449            this.packageName = packageName;
10450            this.dataAppName = dataAppName;
10451            this.appId = appId;
10452            this.seinfo = seinfo;
10453        }
10454    }
10455
10456    class InstallParams extends HandlerParams {
10457        final OriginInfo origin;
10458        final MoveInfo move;
10459        final IPackageInstallObserver2 observer;
10460        int installFlags;
10461        final String installerPackageName;
10462        final String volumeUuid;
10463        final VerificationParams verificationParams;
10464        private InstallArgs mArgs;
10465        private int mRet;
10466        final String packageAbiOverride;
10467        final String[] grantedRuntimePermissions;
10468
10469
10470        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10471                int installFlags, String installerPackageName, String volumeUuid,
10472                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10473                String[] grantedPermissions) {
10474            super(user);
10475            this.origin = origin;
10476            this.move = move;
10477            this.observer = observer;
10478            this.installFlags = installFlags;
10479            this.installerPackageName = installerPackageName;
10480            this.volumeUuid = volumeUuid;
10481            this.verificationParams = verificationParams;
10482            this.packageAbiOverride = packageAbiOverride;
10483            this.grantedRuntimePermissions = grantedPermissions;
10484        }
10485
10486        @Override
10487        public String toString() {
10488            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10489                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10490        }
10491
10492        public ManifestDigest getManifestDigest() {
10493            if (verificationParams == null) {
10494                return null;
10495            }
10496            return verificationParams.getManifestDigest();
10497        }
10498
10499        private int installLocationPolicy(PackageInfoLite pkgLite) {
10500            String packageName = pkgLite.packageName;
10501            int installLocation = pkgLite.installLocation;
10502            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10503            // reader
10504            synchronized (mPackages) {
10505                PackageParser.Package pkg = mPackages.get(packageName);
10506                if (pkg != null) {
10507                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10508                        // Check for downgrading.
10509                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10510                            try {
10511                                checkDowngrade(pkg, pkgLite);
10512                            } catch (PackageManagerException e) {
10513                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10514                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10515                            }
10516                        }
10517                        // Check for updated system application.
10518                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10519                            if (onSd) {
10520                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10521                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10522                            }
10523                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10524                        } else {
10525                            if (onSd) {
10526                                // Install flag overrides everything.
10527                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10528                            }
10529                            // If current upgrade specifies particular preference
10530                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10531                                // Application explicitly specified internal.
10532                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10533                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10534                                // App explictly prefers external. Let policy decide
10535                            } else {
10536                                // Prefer previous location
10537                                if (isExternal(pkg)) {
10538                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10539                                }
10540                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10541                            }
10542                        }
10543                    } else {
10544                        // Invalid install. Return error code
10545                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10546                    }
10547                }
10548            }
10549            // All the special cases have been taken care of.
10550            // Return result based on recommended install location.
10551            if (onSd) {
10552                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10553            }
10554            return pkgLite.recommendedInstallLocation;
10555        }
10556
10557        /*
10558         * Invoke remote method to get package information and install
10559         * location values. Override install location based on default
10560         * policy if needed and then create install arguments based
10561         * on the install location.
10562         */
10563        public void handleStartCopy() throws RemoteException {
10564            int ret = PackageManager.INSTALL_SUCCEEDED;
10565
10566            // If we're already staged, we've firmly committed to an install location
10567            if (origin.staged) {
10568                if (origin.file != null) {
10569                    installFlags |= PackageManager.INSTALL_INTERNAL;
10570                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10571                } else if (origin.cid != null) {
10572                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10573                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10574                } else {
10575                    throw new IllegalStateException("Invalid stage location");
10576                }
10577            }
10578
10579            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10580            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10581
10582            PackageInfoLite pkgLite = null;
10583
10584            if (onInt && onSd) {
10585                // Check if both bits are set.
10586                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10587                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10588            } else {
10589                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10590                        packageAbiOverride);
10591
10592                /*
10593                 * If we have too little free space, try to free cache
10594                 * before giving up.
10595                 */
10596                if (!origin.staged && pkgLite.recommendedInstallLocation
10597                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10598                    // TODO: focus freeing disk space on the target device
10599                    final StorageManager storage = StorageManager.from(mContext);
10600                    final long lowThreshold = storage.getStorageLowBytes(
10601                            Environment.getDataDirectory());
10602
10603                    final long sizeBytes = mContainerService.calculateInstalledSize(
10604                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10605
10606                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10607                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10608                                installFlags, packageAbiOverride);
10609                    }
10610
10611                    /*
10612                     * The cache free must have deleted the file we
10613                     * downloaded to install.
10614                     *
10615                     * TODO: fix the "freeCache" call to not delete
10616                     *       the file we care about.
10617                     */
10618                    if (pkgLite.recommendedInstallLocation
10619                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10620                        pkgLite.recommendedInstallLocation
10621                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10622                    }
10623                }
10624            }
10625
10626            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10627                int loc = pkgLite.recommendedInstallLocation;
10628                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10629                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10630                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10631                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10632                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10633                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10634                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10635                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10636                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10637                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10638                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10639                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10640                } else {
10641                    // Override with defaults if needed.
10642                    loc = installLocationPolicy(pkgLite);
10643                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10644                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10645                    } else if (!onSd && !onInt) {
10646                        // Override install location with flags
10647                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10648                            // Set the flag to install on external media.
10649                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10650                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10651                        } else {
10652                            // Make sure the flag for installing on external
10653                            // media is unset
10654                            installFlags |= PackageManager.INSTALL_INTERNAL;
10655                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10656                        }
10657                    }
10658                }
10659            }
10660
10661            final InstallArgs args = createInstallArgs(this);
10662            mArgs = args;
10663
10664            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10665                 /*
10666                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10667                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10668                 */
10669                int userIdentifier = getUser().getIdentifier();
10670                if (userIdentifier == UserHandle.USER_ALL
10671                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10672                    userIdentifier = UserHandle.USER_OWNER;
10673                }
10674
10675                /*
10676                 * Determine if we have any installed package verifiers. If we
10677                 * do, then we'll defer to them to verify the packages.
10678                 */
10679                final int requiredUid = mRequiredVerifierPackage == null ? -1
10680                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10681                if (!origin.existing && requiredUid != -1
10682                        && isVerificationEnabled(userIdentifier, installFlags)) {
10683                    final Intent verification = new Intent(
10684                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10685                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10686                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10687                            PACKAGE_MIME_TYPE);
10688                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10689
10690                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10691                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10692                            0 /* TODO: Which userId? */);
10693
10694                    if (DEBUG_VERIFY) {
10695                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10696                                + verification.toString() + " with " + pkgLite.verifiers.length
10697                                + " optional verifiers");
10698                    }
10699
10700                    final int verificationId = mPendingVerificationToken++;
10701
10702                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10703
10704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10705                            installerPackageName);
10706
10707                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10708                            installFlags);
10709
10710                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10711                            pkgLite.packageName);
10712
10713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10714                            pkgLite.versionCode);
10715
10716                    if (verificationParams != null) {
10717                        if (verificationParams.getVerificationURI() != null) {
10718                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10719                                 verificationParams.getVerificationURI());
10720                        }
10721                        if (verificationParams.getOriginatingURI() != null) {
10722                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10723                                  verificationParams.getOriginatingURI());
10724                        }
10725                        if (verificationParams.getReferrer() != null) {
10726                            verification.putExtra(Intent.EXTRA_REFERRER,
10727                                  verificationParams.getReferrer());
10728                        }
10729                        if (verificationParams.getOriginatingUid() >= 0) {
10730                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10731                                  verificationParams.getOriginatingUid());
10732                        }
10733                        if (verificationParams.getInstallerUid() >= 0) {
10734                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10735                                  verificationParams.getInstallerUid());
10736                        }
10737                    }
10738
10739                    final PackageVerificationState verificationState = new PackageVerificationState(
10740                            requiredUid, args);
10741
10742                    mPendingVerification.append(verificationId, verificationState);
10743
10744                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10745                            receivers, verificationState);
10746
10747                    // Apps installed for "all" users use the device owner to verify the app
10748                    UserHandle verifierUser = getUser();
10749                    if (verifierUser == UserHandle.ALL) {
10750                        verifierUser = UserHandle.OWNER;
10751                    }
10752
10753                    /*
10754                     * If any sufficient verifiers were listed in the package
10755                     * manifest, attempt to ask them.
10756                     */
10757                    if (sufficientVerifiers != null) {
10758                        final int N = sufficientVerifiers.size();
10759                        if (N == 0) {
10760                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10761                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10762                        } else {
10763                            for (int i = 0; i < N; i++) {
10764                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10765
10766                                final Intent sufficientIntent = new Intent(verification);
10767                                sufficientIntent.setComponent(verifierComponent);
10768                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10769                            }
10770                        }
10771                    }
10772
10773                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10774                            mRequiredVerifierPackage, receivers);
10775                    if (ret == PackageManager.INSTALL_SUCCEEDED
10776                            && mRequiredVerifierPackage != null) {
10777                        /*
10778                         * Send the intent to the required verification agent,
10779                         * but only start the verification timeout after the
10780                         * target BroadcastReceivers have run.
10781                         */
10782                        verification.setComponent(requiredVerifierComponent);
10783                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10784                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10785                                new BroadcastReceiver() {
10786                                    @Override
10787                                    public void onReceive(Context context, Intent intent) {
10788                                        final Message msg = mHandler
10789                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10790                                        msg.arg1 = verificationId;
10791                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10792                                    }
10793                                }, null, 0, null, null);
10794
10795                        /*
10796                         * We don't want the copy to proceed until verification
10797                         * succeeds, so null out this field.
10798                         */
10799                        mArgs = null;
10800                    }
10801                } else {
10802                    /*
10803                     * No package verification is enabled, so immediately start
10804                     * the remote call to initiate copy using temporary file.
10805                     */
10806                    ret = args.copyApk(mContainerService, true);
10807                }
10808            }
10809
10810            mRet = ret;
10811        }
10812
10813        @Override
10814        void handleReturnCode() {
10815            // If mArgs is null, then MCS couldn't be reached. When it
10816            // reconnects, it will try again to install. At that point, this
10817            // will succeed.
10818            if (mArgs != null) {
10819                processPendingInstall(mArgs, mRet);
10820            }
10821        }
10822
10823        @Override
10824        void handleServiceError() {
10825            mArgs = createInstallArgs(this);
10826            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10827        }
10828
10829        public boolean isForwardLocked() {
10830            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10831        }
10832    }
10833
10834    /**
10835     * Used during creation of InstallArgs
10836     *
10837     * @param installFlags package installation flags
10838     * @return true if should be installed on external storage
10839     */
10840    private static boolean installOnExternalAsec(int installFlags) {
10841        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10842            return false;
10843        }
10844        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10845            return true;
10846        }
10847        return false;
10848    }
10849
10850    /**
10851     * Used during creation of InstallArgs
10852     *
10853     * @param installFlags package installation flags
10854     * @return true if should be installed as forward locked
10855     */
10856    private static boolean installForwardLocked(int installFlags) {
10857        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10858    }
10859
10860    private InstallArgs createInstallArgs(InstallParams params) {
10861        if (params.move != null) {
10862            return new MoveInstallArgs(params);
10863        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10864            return new AsecInstallArgs(params);
10865        } else {
10866            return new FileInstallArgs(params);
10867        }
10868    }
10869
10870    /**
10871     * Create args that describe an existing installed package. Typically used
10872     * when cleaning up old installs, or used as a move source.
10873     */
10874    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10875            String resourcePath, String[] instructionSets) {
10876        final boolean isInAsec;
10877        if (installOnExternalAsec(installFlags)) {
10878            /* Apps on SD card are always in ASEC containers. */
10879            isInAsec = true;
10880        } else if (installForwardLocked(installFlags)
10881                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10882            /*
10883             * Forward-locked apps are only in ASEC containers if they're the
10884             * new style
10885             */
10886            isInAsec = true;
10887        } else {
10888            isInAsec = false;
10889        }
10890
10891        if (isInAsec) {
10892            return new AsecInstallArgs(codePath, instructionSets,
10893                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10894        } else {
10895            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10896        }
10897    }
10898
10899    static abstract class InstallArgs {
10900        /** @see InstallParams#origin */
10901        final OriginInfo origin;
10902        /** @see InstallParams#move */
10903        final MoveInfo move;
10904
10905        final IPackageInstallObserver2 observer;
10906        // Always refers to PackageManager flags only
10907        final int installFlags;
10908        final String installerPackageName;
10909        final String volumeUuid;
10910        final ManifestDigest manifestDigest;
10911        final UserHandle user;
10912        final String abiOverride;
10913        final String[] installGrantPermissions;
10914
10915        // The list of instruction sets supported by this app. This is currently
10916        // only used during the rmdex() phase to clean up resources. We can get rid of this
10917        // if we move dex files under the common app path.
10918        /* nullable */ String[] instructionSets;
10919
10920        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10921                int installFlags, String installerPackageName, String volumeUuid,
10922                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10923                String abiOverride, String[] installGrantPermissions) {
10924            this.origin = origin;
10925            this.move = move;
10926            this.installFlags = installFlags;
10927            this.observer = observer;
10928            this.installerPackageName = installerPackageName;
10929            this.volumeUuid = volumeUuid;
10930            this.manifestDigest = manifestDigest;
10931            this.user = user;
10932            this.instructionSets = instructionSets;
10933            this.abiOverride = abiOverride;
10934            this.installGrantPermissions = installGrantPermissions;
10935        }
10936
10937        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10938        abstract int doPreInstall(int status);
10939
10940        /**
10941         * Rename package into final resting place. All paths on the given
10942         * scanned package should be updated to reflect the rename.
10943         */
10944        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10945        abstract int doPostInstall(int status, int uid);
10946
10947        /** @see PackageSettingBase#codePathString */
10948        abstract String getCodePath();
10949        /** @see PackageSettingBase#resourcePathString */
10950        abstract String getResourcePath();
10951
10952        // Need installer lock especially for dex file removal.
10953        abstract void cleanUpResourcesLI();
10954        abstract boolean doPostDeleteLI(boolean delete);
10955
10956        /**
10957         * Called before the source arguments are copied. This is used mostly
10958         * for MoveParams when it needs to read the source file to put it in the
10959         * destination.
10960         */
10961        int doPreCopy() {
10962            return PackageManager.INSTALL_SUCCEEDED;
10963        }
10964
10965        /**
10966         * Called after the source arguments are copied. This is used mostly for
10967         * MoveParams when it needs to read the source file to put it in the
10968         * destination.
10969         *
10970         * @return
10971         */
10972        int doPostCopy(int uid) {
10973            return PackageManager.INSTALL_SUCCEEDED;
10974        }
10975
10976        protected boolean isFwdLocked() {
10977            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10978        }
10979
10980        protected boolean isExternalAsec() {
10981            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10982        }
10983
10984        UserHandle getUser() {
10985            return user;
10986        }
10987    }
10988
10989    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10990        if (!allCodePaths.isEmpty()) {
10991            if (instructionSets == null) {
10992                throw new IllegalStateException("instructionSet == null");
10993            }
10994            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10995            for (String codePath : allCodePaths) {
10996                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10997                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10998                    if (retCode < 0) {
10999                        Slog.w(TAG, "Couldn't remove dex file for package: "
11000                                + " at location " + codePath + ", retcode=" + retCode);
11001                        // we don't consider this to be a failure of the core package deletion
11002                    }
11003                }
11004            }
11005        }
11006    }
11007
11008    /**
11009     * Logic to handle installation of non-ASEC applications, including copying
11010     * and renaming logic.
11011     */
11012    class FileInstallArgs extends InstallArgs {
11013        private File codeFile;
11014        private File resourceFile;
11015
11016        // Example topology:
11017        // /data/app/com.example/base.apk
11018        // /data/app/com.example/split_foo.apk
11019        // /data/app/com.example/lib/arm/libfoo.so
11020        // /data/app/com.example/lib/arm64/libfoo.so
11021        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11022
11023        /** New install */
11024        FileInstallArgs(InstallParams params) {
11025            super(params.origin, params.move, params.observer, params.installFlags,
11026                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11027                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11028                    params.grantedRuntimePermissions);
11029            if (isFwdLocked()) {
11030                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11031            }
11032        }
11033
11034        /** Existing install */
11035        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11036            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11037                    null, null);
11038            this.codeFile = (codePath != null) ? new File(codePath) : null;
11039            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11040        }
11041
11042        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11043            if (origin.staged) {
11044                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11045                codeFile = origin.file;
11046                resourceFile = origin.file;
11047                return PackageManager.INSTALL_SUCCEEDED;
11048            }
11049
11050            try {
11051                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11052                codeFile = tempDir;
11053                resourceFile = tempDir;
11054            } catch (IOException e) {
11055                Slog.w(TAG, "Failed to create copy file: " + e);
11056                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11057            }
11058
11059            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11060                @Override
11061                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11062                    if (!FileUtils.isValidExtFilename(name)) {
11063                        throw new IllegalArgumentException("Invalid filename: " + name);
11064                    }
11065                    try {
11066                        final File file = new File(codeFile, name);
11067                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11068                                O_RDWR | O_CREAT, 0644);
11069                        Os.chmod(file.getAbsolutePath(), 0644);
11070                        return new ParcelFileDescriptor(fd);
11071                    } catch (ErrnoException e) {
11072                        throw new RemoteException("Failed to open: " + e.getMessage());
11073                    }
11074                }
11075            };
11076
11077            int ret = PackageManager.INSTALL_SUCCEEDED;
11078            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11079            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11080                Slog.e(TAG, "Failed to copy package");
11081                return ret;
11082            }
11083
11084            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11085            NativeLibraryHelper.Handle handle = null;
11086            try {
11087                handle = NativeLibraryHelper.Handle.create(codeFile);
11088                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11089                        abiOverride);
11090            } catch (IOException e) {
11091                Slog.e(TAG, "Copying native libraries failed", e);
11092                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11093            } finally {
11094                IoUtils.closeQuietly(handle);
11095            }
11096
11097            return ret;
11098        }
11099
11100        int doPreInstall(int status) {
11101            if (status != PackageManager.INSTALL_SUCCEEDED) {
11102                cleanUp();
11103            }
11104            return status;
11105        }
11106
11107        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11108            if (status != PackageManager.INSTALL_SUCCEEDED) {
11109                cleanUp();
11110                return false;
11111            }
11112
11113            final File targetDir = codeFile.getParentFile();
11114            final File beforeCodeFile = codeFile;
11115            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11116
11117            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11118            try {
11119                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11120            } catch (ErrnoException e) {
11121                Slog.w(TAG, "Failed to rename", e);
11122                return false;
11123            }
11124
11125            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11126                Slog.w(TAG, "Failed to restorecon");
11127                return false;
11128            }
11129
11130            // Reflect the rename internally
11131            codeFile = afterCodeFile;
11132            resourceFile = afterCodeFile;
11133
11134            // Reflect the rename in scanned details
11135            pkg.codePath = afterCodeFile.getAbsolutePath();
11136            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11137                    pkg.baseCodePath);
11138            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11139                    pkg.splitCodePaths);
11140
11141            // Reflect the rename in app info
11142            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11143            pkg.applicationInfo.setCodePath(pkg.codePath);
11144            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11145            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11146            pkg.applicationInfo.setResourcePath(pkg.codePath);
11147            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11148            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11149
11150            return true;
11151        }
11152
11153        int doPostInstall(int status, int uid) {
11154            if (status != PackageManager.INSTALL_SUCCEEDED) {
11155                cleanUp();
11156            }
11157            return status;
11158        }
11159
11160        @Override
11161        String getCodePath() {
11162            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11163        }
11164
11165        @Override
11166        String getResourcePath() {
11167            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11168        }
11169
11170        private boolean cleanUp() {
11171            if (codeFile == null || !codeFile.exists()) {
11172                return false;
11173            }
11174
11175            if (codeFile.isDirectory()) {
11176                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11177            } else {
11178                codeFile.delete();
11179            }
11180
11181            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11182                resourceFile.delete();
11183            }
11184
11185            return true;
11186        }
11187
11188        void cleanUpResourcesLI() {
11189            // Try enumerating all code paths before deleting
11190            List<String> allCodePaths = Collections.EMPTY_LIST;
11191            if (codeFile != null && codeFile.exists()) {
11192                try {
11193                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11194                    allCodePaths = pkg.getAllCodePaths();
11195                } catch (PackageParserException e) {
11196                    // Ignored; we tried our best
11197                }
11198            }
11199
11200            cleanUp();
11201            removeDexFiles(allCodePaths, instructionSets);
11202        }
11203
11204        boolean doPostDeleteLI(boolean delete) {
11205            // XXX err, shouldn't we respect the delete flag?
11206            cleanUpResourcesLI();
11207            return true;
11208        }
11209    }
11210
11211    private boolean isAsecExternal(String cid) {
11212        final String asecPath = PackageHelper.getSdFilesystem(cid);
11213        return !asecPath.startsWith(mAsecInternalPath);
11214    }
11215
11216    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11217            PackageManagerException {
11218        if (copyRet < 0) {
11219            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11220                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11221                throw new PackageManagerException(copyRet, message);
11222            }
11223        }
11224    }
11225
11226    /**
11227     * Extract the MountService "container ID" from the full code path of an
11228     * .apk.
11229     */
11230    static String cidFromCodePath(String fullCodePath) {
11231        int eidx = fullCodePath.lastIndexOf("/");
11232        String subStr1 = fullCodePath.substring(0, eidx);
11233        int sidx = subStr1.lastIndexOf("/");
11234        return subStr1.substring(sidx+1, eidx);
11235    }
11236
11237    /**
11238     * Logic to handle installation of ASEC applications, including copying and
11239     * renaming logic.
11240     */
11241    class AsecInstallArgs extends InstallArgs {
11242        static final String RES_FILE_NAME = "pkg.apk";
11243        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11244
11245        String cid;
11246        String packagePath;
11247        String resourcePath;
11248
11249        /** New install */
11250        AsecInstallArgs(InstallParams params) {
11251            super(params.origin, params.move, params.observer, params.installFlags,
11252                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11253                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11254                    params.grantedRuntimePermissions);
11255        }
11256
11257        /** Existing install */
11258        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11259                        boolean isExternal, boolean isForwardLocked) {
11260            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11261                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11262                    instructionSets, null, null);
11263            // Hackily pretend we're still looking at a full code path
11264            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11265                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11266            }
11267
11268            // Extract cid from fullCodePath
11269            int eidx = fullCodePath.lastIndexOf("/");
11270            String subStr1 = fullCodePath.substring(0, eidx);
11271            int sidx = subStr1.lastIndexOf("/");
11272            cid = subStr1.substring(sidx+1, eidx);
11273            setMountPath(subStr1);
11274        }
11275
11276        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11277            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11278                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11279                    instructionSets, null, null);
11280            this.cid = cid;
11281            setMountPath(PackageHelper.getSdDir(cid));
11282        }
11283
11284        void createCopyFile() {
11285            cid = mInstallerService.allocateExternalStageCidLegacy();
11286        }
11287
11288        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11289            if (origin.staged) {
11290                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11291                cid = origin.cid;
11292                setMountPath(PackageHelper.getSdDir(cid));
11293                return PackageManager.INSTALL_SUCCEEDED;
11294            }
11295
11296            if (temp) {
11297                createCopyFile();
11298            } else {
11299                /*
11300                 * Pre-emptively destroy the container since it's destroyed if
11301                 * copying fails due to it existing anyway.
11302                 */
11303                PackageHelper.destroySdDir(cid);
11304            }
11305
11306            final String newMountPath = imcs.copyPackageToContainer(
11307                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11308                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11309
11310            if (newMountPath != null) {
11311                setMountPath(newMountPath);
11312                return PackageManager.INSTALL_SUCCEEDED;
11313            } else {
11314                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11315            }
11316        }
11317
11318        @Override
11319        String getCodePath() {
11320            return packagePath;
11321        }
11322
11323        @Override
11324        String getResourcePath() {
11325            return resourcePath;
11326        }
11327
11328        int doPreInstall(int status) {
11329            if (status != PackageManager.INSTALL_SUCCEEDED) {
11330                // Destroy container
11331                PackageHelper.destroySdDir(cid);
11332            } else {
11333                boolean mounted = PackageHelper.isContainerMounted(cid);
11334                if (!mounted) {
11335                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11336                            Process.SYSTEM_UID);
11337                    if (newMountPath != null) {
11338                        setMountPath(newMountPath);
11339                    } else {
11340                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11341                    }
11342                }
11343            }
11344            return status;
11345        }
11346
11347        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11348            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11349            String newMountPath = null;
11350            if (PackageHelper.isContainerMounted(cid)) {
11351                // Unmount the container
11352                if (!PackageHelper.unMountSdDir(cid)) {
11353                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11354                    return false;
11355                }
11356            }
11357            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11358                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11359                        " which might be stale. Will try to clean up.");
11360                // Clean up the stale container and proceed to recreate.
11361                if (!PackageHelper.destroySdDir(newCacheId)) {
11362                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11363                    return false;
11364                }
11365                // Successfully cleaned up stale container. Try to rename again.
11366                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11367                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11368                            + " inspite of cleaning it up.");
11369                    return false;
11370                }
11371            }
11372            if (!PackageHelper.isContainerMounted(newCacheId)) {
11373                Slog.w(TAG, "Mounting container " + newCacheId);
11374                newMountPath = PackageHelper.mountSdDir(newCacheId,
11375                        getEncryptKey(), Process.SYSTEM_UID);
11376            } else {
11377                newMountPath = PackageHelper.getSdDir(newCacheId);
11378            }
11379            if (newMountPath == null) {
11380                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11381                return false;
11382            }
11383            Log.i(TAG, "Succesfully renamed " + cid +
11384                    " to " + newCacheId +
11385                    " at new path: " + newMountPath);
11386            cid = newCacheId;
11387
11388            final File beforeCodeFile = new File(packagePath);
11389            setMountPath(newMountPath);
11390            final File afterCodeFile = new File(packagePath);
11391
11392            // Reflect the rename in scanned details
11393            pkg.codePath = afterCodeFile.getAbsolutePath();
11394            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11395                    pkg.baseCodePath);
11396            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11397                    pkg.splitCodePaths);
11398
11399            // Reflect the rename in app info
11400            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11401            pkg.applicationInfo.setCodePath(pkg.codePath);
11402            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11403            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11404            pkg.applicationInfo.setResourcePath(pkg.codePath);
11405            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11406            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11407
11408            return true;
11409        }
11410
11411        private void setMountPath(String mountPath) {
11412            final File mountFile = new File(mountPath);
11413
11414            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11415            if (monolithicFile.exists()) {
11416                packagePath = monolithicFile.getAbsolutePath();
11417                if (isFwdLocked()) {
11418                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11419                } else {
11420                    resourcePath = packagePath;
11421                }
11422            } else {
11423                packagePath = mountFile.getAbsolutePath();
11424                resourcePath = packagePath;
11425            }
11426        }
11427
11428        int doPostInstall(int status, int uid) {
11429            if (status != PackageManager.INSTALL_SUCCEEDED) {
11430                cleanUp();
11431            } else {
11432                final int groupOwner;
11433                final String protectedFile;
11434                if (isFwdLocked()) {
11435                    groupOwner = UserHandle.getSharedAppGid(uid);
11436                    protectedFile = RES_FILE_NAME;
11437                } else {
11438                    groupOwner = -1;
11439                    protectedFile = null;
11440                }
11441
11442                if (uid < Process.FIRST_APPLICATION_UID
11443                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11444                    Slog.e(TAG, "Failed to finalize " + cid);
11445                    PackageHelper.destroySdDir(cid);
11446                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11447                }
11448
11449                boolean mounted = PackageHelper.isContainerMounted(cid);
11450                if (!mounted) {
11451                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11452                }
11453            }
11454            return status;
11455        }
11456
11457        private void cleanUp() {
11458            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11459
11460            // Destroy secure container
11461            PackageHelper.destroySdDir(cid);
11462        }
11463
11464        private List<String> getAllCodePaths() {
11465            final File codeFile = new File(getCodePath());
11466            if (codeFile != null && codeFile.exists()) {
11467                try {
11468                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11469                    return pkg.getAllCodePaths();
11470                } catch (PackageParserException e) {
11471                    // Ignored; we tried our best
11472                }
11473            }
11474            return Collections.EMPTY_LIST;
11475        }
11476
11477        void cleanUpResourcesLI() {
11478            // Enumerate all code paths before deleting
11479            cleanUpResourcesLI(getAllCodePaths());
11480        }
11481
11482        private void cleanUpResourcesLI(List<String> allCodePaths) {
11483            cleanUp();
11484            removeDexFiles(allCodePaths, instructionSets);
11485        }
11486
11487        String getPackageName() {
11488            return getAsecPackageName(cid);
11489        }
11490
11491        boolean doPostDeleteLI(boolean delete) {
11492            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11493            final List<String> allCodePaths = getAllCodePaths();
11494            boolean mounted = PackageHelper.isContainerMounted(cid);
11495            if (mounted) {
11496                // Unmount first
11497                if (PackageHelper.unMountSdDir(cid)) {
11498                    mounted = false;
11499                }
11500            }
11501            if (!mounted && delete) {
11502                cleanUpResourcesLI(allCodePaths);
11503            }
11504            return !mounted;
11505        }
11506
11507        @Override
11508        int doPreCopy() {
11509            if (isFwdLocked()) {
11510                if (!PackageHelper.fixSdPermissions(cid,
11511                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11512                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11513                }
11514            }
11515
11516            return PackageManager.INSTALL_SUCCEEDED;
11517        }
11518
11519        @Override
11520        int doPostCopy(int uid) {
11521            if (isFwdLocked()) {
11522                if (uid < Process.FIRST_APPLICATION_UID
11523                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11524                                RES_FILE_NAME)) {
11525                    Slog.e(TAG, "Failed to finalize " + cid);
11526                    PackageHelper.destroySdDir(cid);
11527                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11528                }
11529            }
11530
11531            return PackageManager.INSTALL_SUCCEEDED;
11532        }
11533    }
11534
11535    /**
11536     * Logic to handle movement of existing installed applications.
11537     */
11538    class MoveInstallArgs extends InstallArgs {
11539        private File codeFile;
11540        private File resourceFile;
11541
11542        /** New install */
11543        MoveInstallArgs(InstallParams params) {
11544            super(params.origin, params.move, params.observer, params.installFlags,
11545                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11546                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11547                    params.grantedRuntimePermissions);
11548        }
11549
11550        int copyApk(IMediaContainerService imcs, boolean temp) {
11551            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11552                    + move.fromUuid + " to " + move.toUuid);
11553            synchronized (mInstaller) {
11554                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11555                        move.dataAppName, move.appId, move.seinfo) != 0) {
11556                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11557                }
11558            }
11559
11560            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11561            resourceFile = codeFile;
11562            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11563
11564            return PackageManager.INSTALL_SUCCEEDED;
11565        }
11566
11567        int doPreInstall(int status) {
11568            if (status != PackageManager.INSTALL_SUCCEEDED) {
11569                cleanUp(move.toUuid);
11570            }
11571            return status;
11572        }
11573
11574        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11575            if (status != PackageManager.INSTALL_SUCCEEDED) {
11576                cleanUp(move.toUuid);
11577                return false;
11578            }
11579
11580            // Reflect the move in app info
11581            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11582            pkg.applicationInfo.setCodePath(pkg.codePath);
11583            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11584            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11585            pkg.applicationInfo.setResourcePath(pkg.codePath);
11586            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11587            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11588
11589            return true;
11590        }
11591
11592        int doPostInstall(int status, int uid) {
11593            if (status == PackageManager.INSTALL_SUCCEEDED) {
11594                cleanUp(move.fromUuid);
11595            } else {
11596                cleanUp(move.toUuid);
11597            }
11598            return status;
11599        }
11600
11601        @Override
11602        String getCodePath() {
11603            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11604        }
11605
11606        @Override
11607        String getResourcePath() {
11608            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11609        }
11610
11611        private boolean cleanUp(String volumeUuid) {
11612            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11613                    move.dataAppName);
11614            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11615            synchronized (mInstallLock) {
11616                // Clean up both app data and code
11617                removeDataDirsLI(volumeUuid, move.packageName);
11618                if (codeFile.isDirectory()) {
11619                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11620                } else {
11621                    codeFile.delete();
11622                }
11623            }
11624            return true;
11625        }
11626
11627        void cleanUpResourcesLI() {
11628            throw new UnsupportedOperationException();
11629        }
11630
11631        boolean doPostDeleteLI(boolean delete) {
11632            throw new UnsupportedOperationException();
11633        }
11634    }
11635
11636    static String getAsecPackageName(String packageCid) {
11637        int idx = packageCid.lastIndexOf("-");
11638        if (idx == -1) {
11639            return packageCid;
11640        }
11641        return packageCid.substring(0, idx);
11642    }
11643
11644    // Utility method used to create code paths based on package name and available index.
11645    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11646        String idxStr = "";
11647        int idx = 1;
11648        // Fall back to default value of idx=1 if prefix is not
11649        // part of oldCodePath
11650        if (oldCodePath != null) {
11651            String subStr = oldCodePath;
11652            // Drop the suffix right away
11653            if (suffix != null && subStr.endsWith(suffix)) {
11654                subStr = subStr.substring(0, subStr.length() - suffix.length());
11655            }
11656            // If oldCodePath already contains prefix find out the
11657            // ending index to either increment or decrement.
11658            int sidx = subStr.lastIndexOf(prefix);
11659            if (sidx != -1) {
11660                subStr = subStr.substring(sidx + prefix.length());
11661                if (subStr != null) {
11662                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11663                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11664                    }
11665                    try {
11666                        idx = Integer.parseInt(subStr);
11667                        if (idx <= 1) {
11668                            idx++;
11669                        } else {
11670                            idx--;
11671                        }
11672                    } catch(NumberFormatException e) {
11673                    }
11674                }
11675            }
11676        }
11677        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11678        return prefix + idxStr;
11679    }
11680
11681    private File getNextCodePath(File targetDir, String packageName) {
11682        int suffix = 1;
11683        File result;
11684        do {
11685            result = new File(targetDir, packageName + "-" + suffix);
11686            suffix++;
11687        } while (result.exists());
11688        return result;
11689    }
11690
11691    // Utility method that returns the relative package path with respect
11692    // to the installation directory. Like say for /data/data/com.test-1.apk
11693    // string com.test-1 is returned.
11694    static String deriveCodePathName(String codePath) {
11695        if (codePath == null) {
11696            return null;
11697        }
11698        final File codeFile = new File(codePath);
11699        final String name = codeFile.getName();
11700        if (codeFile.isDirectory()) {
11701            return name;
11702        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11703            final int lastDot = name.lastIndexOf('.');
11704            return name.substring(0, lastDot);
11705        } else {
11706            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11707            return null;
11708        }
11709    }
11710
11711    class PackageInstalledInfo {
11712        String name;
11713        int uid;
11714        // The set of users that originally had this package installed.
11715        int[] origUsers;
11716        // The set of users that now have this package installed.
11717        int[] newUsers;
11718        PackageParser.Package pkg;
11719        int returnCode;
11720        String returnMsg;
11721        PackageRemovedInfo removedInfo;
11722
11723        public void setError(int code, String msg) {
11724            returnCode = code;
11725            returnMsg = msg;
11726            Slog.w(TAG, msg);
11727        }
11728
11729        public void setError(String msg, PackageParserException e) {
11730            returnCode = e.error;
11731            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11732            Slog.w(TAG, msg, e);
11733        }
11734
11735        public void setError(String msg, PackageManagerException e) {
11736            returnCode = e.error;
11737            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11738            Slog.w(TAG, msg, e);
11739        }
11740
11741        // In some error cases we want to convey more info back to the observer
11742        String origPackage;
11743        String origPermission;
11744    }
11745
11746    /*
11747     * Install a non-existing package.
11748     */
11749    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11750            UserHandle user, String installerPackageName, String volumeUuid,
11751            PackageInstalledInfo res) {
11752        // Remember this for later, in case we need to rollback this install
11753        String pkgName = pkg.packageName;
11754
11755        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11756        final boolean dataDirExists = Environment
11757                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11758        synchronized(mPackages) {
11759            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11760                // A package with the same name is already installed, though
11761                // it has been renamed to an older name.  The package we
11762                // are trying to install should be installed as an update to
11763                // the existing one, but that has not been requested, so bail.
11764                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11765                        + " without first uninstalling package running as "
11766                        + mSettings.mRenamedPackages.get(pkgName));
11767                return;
11768            }
11769            if (mPackages.containsKey(pkgName)) {
11770                // Don't allow installation over an existing package with the same name.
11771                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11772                        + " without first uninstalling.");
11773                return;
11774            }
11775        }
11776
11777        try {
11778            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11779                    System.currentTimeMillis(), user);
11780
11781            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11782            // delete the partially installed application. the data directory will have to be
11783            // restored if it was already existing
11784            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11785                // remove package from internal structures.  Note that we want deletePackageX to
11786                // delete the package data and cache directories that it created in
11787                // scanPackageLocked, unless those directories existed before we even tried to
11788                // install.
11789                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11790                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11791                                res.removedInfo, true);
11792            }
11793
11794        } catch (PackageManagerException e) {
11795            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11796        }
11797    }
11798
11799    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11800        // Can't rotate keys during boot or if sharedUser.
11801        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11802                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11803            return false;
11804        }
11805        // app is using upgradeKeySets; make sure all are valid
11806        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11807        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11808        for (int i = 0; i < upgradeKeySets.length; i++) {
11809            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11810                Slog.wtf(TAG, "Package "
11811                         + (oldPs.name != null ? oldPs.name : "<null>")
11812                         + " contains upgrade-key-set reference to unknown key-set: "
11813                         + upgradeKeySets[i]
11814                         + " reverting to signatures check.");
11815                return false;
11816            }
11817        }
11818        return true;
11819    }
11820
11821    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11822        // Upgrade keysets are being used.  Determine if new package has a superset of the
11823        // required keys.
11824        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11825        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11826        for (int i = 0; i < upgradeKeySets.length; i++) {
11827            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11828            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11829                return true;
11830            }
11831        }
11832        return false;
11833    }
11834
11835    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11836            UserHandle user, String installerPackageName, String volumeUuid,
11837            PackageInstalledInfo res) {
11838        final PackageParser.Package oldPackage;
11839        final String pkgName = pkg.packageName;
11840        final int[] allUsers;
11841        final boolean[] perUserInstalled;
11842
11843        // First find the old package info and check signatures
11844        synchronized(mPackages) {
11845            oldPackage = mPackages.get(pkgName);
11846            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11847            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11848            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11849                if(!checkUpgradeKeySetLP(ps, pkg)) {
11850                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11851                            "New package not signed by keys specified by upgrade-keysets: "
11852                            + pkgName);
11853                    return;
11854                }
11855            } else {
11856                // default to original signature matching
11857                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11858                    != PackageManager.SIGNATURE_MATCH) {
11859                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11860                            "New package has a different signature: " + pkgName);
11861                    return;
11862                }
11863            }
11864
11865            // In case of rollback, remember per-user/profile install state
11866            allUsers = sUserManager.getUserIds();
11867            perUserInstalled = new boolean[allUsers.length];
11868            for (int i = 0; i < allUsers.length; i++) {
11869                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11870            }
11871        }
11872
11873        boolean sysPkg = (isSystemApp(oldPackage));
11874        if (sysPkg) {
11875            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11876                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11877        } else {
11878            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11879                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11880        }
11881    }
11882
11883    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11884            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11885            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11886            String volumeUuid, PackageInstalledInfo res) {
11887        String pkgName = deletedPackage.packageName;
11888        boolean deletedPkg = true;
11889        boolean updatedSettings = false;
11890
11891        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11892                + deletedPackage);
11893        long origUpdateTime;
11894        if (pkg.mExtras != null) {
11895            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11896        } else {
11897            origUpdateTime = 0;
11898        }
11899
11900        // First delete the existing package while retaining the data directory
11901        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11902                res.removedInfo, true)) {
11903            // If the existing package wasn't successfully deleted
11904            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11905            deletedPkg = false;
11906        } else {
11907            // Successfully deleted the old package; proceed with replace.
11908
11909            // If deleted package lived in a container, give users a chance to
11910            // relinquish resources before killing.
11911            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11912                if (DEBUG_INSTALL) {
11913                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11914                }
11915                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11916                final ArrayList<String> pkgList = new ArrayList<String>(1);
11917                pkgList.add(deletedPackage.applicationInfo.packageName);
11918                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11919            }
11920
11921            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11922            try {
11923                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11924                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11925                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11926                        perUserInstalled, res, user);
11927                updatedSettings = true;
11928            } catch (PackageManagerException e) {
11929                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11930            }
11931        }
11932
11933        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11934            // remove package from internal structures.  Note that we want deletePackageX to
11935            // delete the package data and cache directories that it created in
11936            // scanPackageLocked, unless those directories existed before we even tried to
11937            // install.
11938            if(updatedSettings) {
11939                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11940                deletePackageLI(
11941                        pkgName, null, true, allUsers, perUserInstalled,
11942                        PackageManager.DELETE_KEEP_DATA,
11943                                res.removedInfo, true);
11944            }
11945            // Since we failed to install the new package we need to restore the old
11946            // package that we deleted.
11947            if (deletedPkg) {
11948                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11949                File restoreFile = new File(deletedPackage.codePath);
11950                // Parse old package
11951                boolean oldExternal = isExternal(deletedPackage);
11952                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11953                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11954                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11955                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11956                try {
11957                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11958                } catch (PackageManagerException e) {
11959                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11960                            + e.getMessage());
11961                    return;
11962                }
11963                // Restore of old package succeeded. Update permissions.
11964                // writer
11965                synchronized (mPackages) {
11966                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11967                            UPDATE_PERMISSIONS_ALL);
11968                    // can downgrade to reader
11969                    mSettings.writeLPr();
11970                }
11971                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11972            }
11973        }
11974    }
11975
11976    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11977            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11978            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11979            String volumeUuid, PackageInstalledInfo res) {
11980        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11981                + ", old=" + deletedPackage);
11982        boolean disabledSystem = false;
11983        boolean updatedSettings = false;
11984        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11985        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11986                != 0) {
11987            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11988        }
11989        String packageName = deletedPackage.packageName;
11990        if (packageName == null) {
11991            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11992                    "Attempt to delete null packageName.");
11993            return;
11994        }
11995        PackageParser.Package oldPkg;
11996        PackageSetting oldPkgSetting;
11997        // reader
11998        synchronized (mPackages) {
11999            oldPkg = mPackages.get(packageName);
12000            oldPkgSetting = mSettings.mPackages.get(packageName);
12001            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12002                    (oldPkgSetting == null)) {
12003                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12004                        "Couldn't find package:" + packageName + " information");
12005                return;
12006            }
12007        }
12008
12009        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12010
12011        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12012        res.removedInfo.removedPackage = packageName;
12013        // Remove existing system package
12014        removePackageLI(oldPkgSetting, true);
12015        // writer
12016        synchronized (mPackages) {
12017            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12018            if (!disabledSystem && deletedPackage != null) {
12019                // We didn't need to disable the .apk as a current system package,
12020                // which means we are replacing another update that is already
12021                // installed.  We need to make sure to delete the older one's .apk.
12022                res.removedInfo.args = createInstallArgsForExisting(0,
12023                        deletedPackage.applicationInfo.getCodePath(),
12024                        deletedPackage.applicationInfo.getResourcePath(),
12025                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12026            } else {
12027                res.removedInfo.args = null;
12028            }
12029        }
12030
12031        // Successfully disabled the old package. Now proceed with re-installation
12032        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12033
12034        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12035        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12036
12037        PackageParser.Package newPackage = null;
12038        try {
12039            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12040            if (newPackage.mExtras != null) {
12041                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12042                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12043                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12044
12045                // is the update attempting to change shared user? that isn't going to work...
12046                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12047                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12048                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12049                            + " to " + newPkgSetting.sharedUser);
12050                    updatedSettings = true;
12051                }
12052            }
12053
12054            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12055                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12056                        perUserInstalled, res, user);
12057                updatedSettings = true;
12058            }
12059
12060        } catch (PackageManagerException e) {
12061            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12062        }
12063
12064        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12065            // Re installation failed. Restore old information
12066            // Remove new pkg information
12067            if (newPackage != null) {
12068                removeInstalledPackageLI(newPackage, true);
12069            }
12070            // Add back the old system package
12071            try {
12072                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12073            } catch (PackageManagerException e) {
12074                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12075            }
12076            // Restore the old system information in Settings
12077            synchronized (mPackages) {
12078                if (disabledSystem) {
12079                    mSettings.enableSystemPackageLPw(packageName);
12080                }
12081                if (updatedSettings) {
12082                    mSettings.setInstallerPackageName(packageName,
12083                            oldPkgSetting.installerPackageName);
12084                }
12085                mSettings.writeLPr();
12086            }
12087        }
12088    }
12089
12090    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12091            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12092            UserHandle user) {
12093        String pkgName = newPackage.packageName;
12094        synchronized (mPackages) {
12095            //write settings. the installStatus will be incomplete at this stage.
12096            //note that the new package setting would have already been
12097            //added to mPackages. It hasn't been persisted yet.
12098            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12099            mSettings.writeLPr();
12100        }
12101
12102        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12103
12104        synchronized (mPackages) {
12105            updatePermissionsLPw(newPackage.packageName, newPackage,
12106                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12107                            ? UPDATE_PERMISSIONS_ALL : 0));
12108            // For system-bundled packages, we assume that installing an upgraded version
12109            // of the package implies that the user actually wants to run that new code,
12110            // so we enable the package.
12111            PackageSetting ps = mSettings.mPackages.get(pkgName);
12112            if (ps != null) {
12113                if (isSystemApp(newPackage)) {
12114                    // NB: implicit assumption that system package upgrades apply to all users
12115                    if (DEBUG_INSTALL) {
12116                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12117                    }
12118                    if (res.origUsers != null) {
12119                        for (int userHandle : res.origUsers) {
12120                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12121                                    userHandle, installerPackageName);
12122                        }
12123                    }
12124                    // Also convey the prior install/uninstall state
12125                    if (allUsers != null && perUserInstalled != null) {
12126                        for (int i = 0; i < allUsers.length; i++) {
12127                            if (DEBUG_INSTALL) {
12128                                Slog.d(TAG, "    user " + allUsers[i]
12129                                        + " => " + perUserInstalled[i]);
12130                            }
12131                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12132                        }
12133                        // these install state changes will be persisted in the
12134                        // upcoming call to mSettings.writeLPr().
12135                    }
12136                }
12137                // It's implied that when a user requests installation, they want the app to be
12138                // installed and enabled.
12139                int userId = user.getIdentifier();
12140                if (userId != UserHandle.USER_ALL) {
12141                    ps.setInstalled(true, userId);
12142                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12143                }
12144            }
12145            res.name = pkgName;
12146            res.uid = newPackage.applicationInfo.uid;
12147            res.pkg = newPackage;
12148            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12149            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12150            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12151            //to update install status
12152            mSettings.writeLPr();
12153        }
12154    }
12155
12156    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12157        final int installFlags = args.installFlags;
12158        final String installerPackageName = args.installerPackageName;
12159        final String volumeUuid = args.volumeUuid;
12160        final File tmpPackageFile = new File(args.getCodePath());
12161        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12162        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12163                || (args.volumeUuid != null));
12164        boolean replace = false;
12165        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12166        if (args.move != null) {
12167            // moving a complete application; perfom an initial scan on the new install location
12168            scanFlags |= SCAN_INITIAL;
12169        }
12170        // Result object to be returned
12171        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12172
12173        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12174        // Retrieve PackageSettings and parse package
12175        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12176                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12177                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12178        PackageParser pp = new PackageParser();
12179        pp.setSeparateProcesses(mSeparateProcesses);
12180        pp.setDisplayMetrics(mMetrics);
12181
12182        final PackageParser.Package pkg;
12183        try {
12184            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12185        } catch (PackageParserException e) {
12186            res.setError("Failed parse during installPackageLI", e);
12187            return;
12188        }
12189
12190        // Mark that we have an install time CPU ABI override.
12191        pkg.cpuAbiOverride = args.abiOverride;
12192
12193        String pkgName = res.name = pkg.packageName;
12194        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12195            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12196                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12197                return;
12198            }
12199        }
12200
12201        try {
12202            pp.collectCertificates(pkg, parseFlags);
12203            pp.collectManifestDigest(pkg);
12204        } catch (PackageParserException e) {
12205            res.setError("Failed collect during installPackageLI", e);
12206            return;
12207        }
12208
12209        /* If the installer passed in a manifest digest, compare it now. */
12210        if (args.manifestDigest != null) {
12211            if (DEBUG_INSTALL) {
12212                final String parsedManifest = pkg.manifestDigest == null ? "null"
12213                        : pkg.manifestDigest.toString();
12214                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12215                        + parsedManifest);
12216            }
12217
12218            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12219                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12220                return;
12221            }
12222        } else if (DEBUG_INSTALL) {
12223            final String parsedManifest = pkg.manifestDigest == null
12224                    ? "null" : pkg.manifestDigest.toString();
12225            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12226        }
12227
12228        // Get rid of all references to package scan path via parser.
12229        pp = null;
12230        String oldCodePath = null;
12231        boolean systemApp = false;
12232        synchronized (mPackages) {
12233            // Check if installing already existing package
12234            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12235                String oldName = mSettings.mRenamedPackages.get(pkgName);
12236                if (pkg.mOriginalPackages != null
12237                        && pkg.mOriginalPackages.contains(oldName)
12238                        && mPackages.containsKey(oldName)) {
12239                    // This package is derived from an original package,
12240                    // and this device has been updating from that original
12241                    // name.  We must continue using the original name, so
12242                    // rename the new package here.
12243                    pkg.setPackageName(oldName);
12244                    pkgName = pkg.packageName;
12245                    replace = true;
12246                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12247                            + oldName + " pkgName=" + pkgName);
12248                } else if (mPackages.containsKey(pkgName)) {
12249                    // This package, under its official name, already exists
12250                    // on the device; we should replace it.
12251                    replace = true;
12252                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12253                }
12254
12255                // Prevent apps opting out from runtime permissions
12256                if (replace) {
12257                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12258                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12259                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12260                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12261                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12262                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12263                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12264                                        + " doesn't support runtime permissions but the old"
12265                                        + " target SDK " + oldTargetSdk + " does.");
12266                        return;
12267                    }
12268                }
12269            }
12270
12271            PackageSetting ps = mSettings.mPackages.get(pkgName);
12272            if (ps != null) {
12273                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12274
12275                // Quick sanity check that we're signed correctly if updating;
12276                // we'll check this again later when scanning, but we want to
12277                // bail early here before tripping over redefined permissions.
12278                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12279                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12280                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12281                                + pkg.packageName + " upgrade keys do not match the "
12282                                + "previously installed version");
12283                        return;
12284                    }
12285                } else {
12286                    try {
12287                        verifySignaturesLP(ps, pkg);
12288                    } catch (PackageManagerException e) {
12289                        res.setError(e.error, e.getMessage());
12290                        return;
12291                    }
12292                }
12293
12294                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12295                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12296                    systemApp = (ps.pkg.applicationInfo.flags &
12297                            ApplicationInfo.FLAG_SYSTEM) != 0;
12298                }
12299                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12300            }
12301
12302            // Check whether the newly-scanned package wants to define an already-defined perm
12303            int N = pkg.permissions.size();
12304            for (int i = N-1; i >= 0; i--) {
12305                PackageParser.Permission perm = pkg.permissions.get(i);
12306                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12307                if (bp != null) {
12308                    // If the defining package is signed with our cert, it's okay.  This
12309                    // also includes the "updating the same package" case, of course.
12310                    // "updating same package" could also involve key-rotation.
12311                    final boolean sigsOk;
12312                    if (bp.sourcePackage.equals(pkg.packageName)
12313                            && (bp.packageSetting instanceof PackageSetting)
12314                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12315                                    scanFlags))) {
12316                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12317                    } else {
12318                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12319                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12320                    }
12321                    if (!sigsOk) {
12322                        // If the owning package is the system itself, we log but allow
12323                        // install to proceed; we fail the install on all other permission
12324                        // redefinitions.
12325                        if (!bp.sourcePackage.equals("android")) {
12326                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12327                                    + pkg.packageName + " attempting to redeclare permission "
12328                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12329                            res.origPermission = perm.info.name;
12330                            res.origPackage = bp.sourcePackage;
12331                            return;
12332                        } else {
12333                            Slog.w(TAG, "Package " + pkg.packageName
12334                                    + " attempting to redeclare system permission "
12335                                    + perm.info.name + "; ignoring new declaration");
12336                            pkg.permissions.remove(i);
12337                        }
12338                    }
12339                }
12340            }
12341
12342        }
12343
12344        if (systemApp && onExternal) {
12345            // Disable updates to system apps on sdcard
12346            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12347                    "Cannot install updates to system apps on sdcard");
12348            return;
12349        }
12350
12351        if (args.move != null) {
12352            // We did an in-place move, so dex is ready to roll
12353            scanFlags |= SCAN_NO_DEX;
12354            scanFlags |= SCAN_MOVE;
12355
12356            synchronized (mPackages) {
12357                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12358                if (ps == null) {
12359                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12360                            "Missing settings for moved package " + pkgName);
12361                }
12362
12363                // We moved the entire application as-is, so bring over the
12364                // previously derived ABI information.
12365                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12366                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12367            }
12368
12369        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12370            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12371            scanFlags |= SCAN_NO_DEX;
12372
12373            try {
12374                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12375                        true /* extract libs */);
12376            } catch (PackageManagerException pme) {
12377                Slog.e(TAG, "Error deriving application ABI", pme);
12378                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12379                return;
12380            }
12381
12382            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12383            int result = mPackageDexOptimizer
12384                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12385                            false /* defer */, false /* inclDependencies */);
12386            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12387                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12388                return;
12389            }
12390        }
12391
12392        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12393            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12394            return;
12395        }
12396
12397        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12398
12399        if (replace) {
12400            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12401                    installerPackageName, volumeUuid, res);
12402        } else {
12403            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12404                    args.user, installerPackageName, volumeUuid, res);
12405        }
12406        synchronized (mPackages) {
12407            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12408            if (ps != null) {
12409                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12410            }
12411        }
12412    }
12413
12414    private void startIntentFilterVerifications(int userId, boolean replacing,
12415            PackageParser.Package pkg) {
12416        if (mIntentFilterVerifierComponent == null) {
12417            Slog.w(TAG, "No IntentFilter verification will not be done as "
12418                    + "there is no IntentFilterVerifier available!");
12419            return;
12420        }
12421
12422        final int verifierUid = getPackageUid(
12423                mIntentFilterVerifierComponent.getPackageName(),
12424                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12425
12426        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12427        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12428        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12429        mHandler.sendMessage(msg);
12430    }
12431
12432    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12433            PackageParser.Package pkg) {
12434        int size = pkg.activities.size();
12435        if (size == 0) {
12436            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12437                    "No activity, so no need to verify any IntentFilter!");
12438            return;
12439        }
12440
12441        final boolean hasDomainURLs = hasDomainURLs(pkg);
12442        if (!hasDomainURLs) {
12443            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12444                    "No domain URLs, so no need to verify any IntentFilter!");
12445            return;
12446        }
12447
12448        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12449                + " if any IntentFilter from the " + size
12450                + " Activities needs verification ...");
12451
12452        int count = 0;
12453        final String packageName = pkg.packageName;
12454
12455        synchronized (mPackages) {
12456            // If this is a new install and we see that we've already run verification for this
12457            // package, we have nothing to do: it means the state was restored from backup.
12458            if (!replacing) {
12459                IntentFilterVerificationInfo ivi =
12460                        mSettings.getIntentFilterVerificationLPr(packageName);
12461                if (ivi != null) {
12462                    if (DEBUG_DOMAIN_VERIFICATION) {
12463                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12464                                + ivi.getStatusString());
12465                    }
12466                    return;
12467                }
12468            }
12469
12470            // If any filters need to be verified, then all need to be.
12471            boolean needToVerify = false;
12472            for (PackageParser.Activity a : pkg.activities) {
12473                for (ActivityIntentInfo filter : a.intents) {
12474                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12475                        if (DEBUG_DOMAIN_VERIFICATION) {
12476                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12477                        }
12478                        needToVerify = true;
12479                        break;
12480                    }
12481                }
12482            }
12483
12484            if (needToVerify) {
12485                final int verificationId = mIntentFilterVerificationToken++;
12486                for (PackageParser.Activity a : pkg.activities) {
12487                    for (ActivityIntentInfo filter : a.intents) {
12488                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12489                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12490                                    "Verification needed for IntentFilter:" + filter.toString());
12491                            mIntentFilterVerifier.addOneIntentFilterVerification(
12492                                    verifierUid, userId, verificationId, filter, packageName);
12493                            count++;
12494                        }
12495                    }
12496                }
12497            }
12498        }
12499
12500        if (count > 0) {
12501            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12502                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12503                    +  " for userId:" + userId);
12504            mIntentFilterVerifier.startVerifications(userId);
12505        } else {
12506            if (DEBUG_DOMAIN_VERIFICATION) {
12507                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12508            }
12509        }
12510    }
12511
12512    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12513        final ComponentName cn  = filter.activity.getComponentName();
12514        final String packageName = cn.getPackageName();
12515
12516        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12517                packageName);
12518        if (ivi == null) {
12519            return true;
12520        }
12521        int status = ivi.getStatus();
12522        switch (status) {
12523            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12524            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12525                return true;
12526
12527            default:
12528                // Nothing to do
12529                return false;
12530        }
12531    }
12532
12533    private static boolean isMultiArch(PackageSetting ps) {
12534        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12535    }
12536
12537    private static boolean isMultiArch(ApplicationInfo info) {
12538        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12539    }
12540
12541    private static boolean isExternal(PackageParser.Package pkg) {
12542        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12543    }
12544
12545    private static boolean isExternal(PackageSetting ps) {
12546        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12547    }
12548
12549    private static boolean isExternal(ApplicationInfo info) {
12550        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12551    }
12552
12553    private static boolean isSystemApp(PackageParser.Package pkg) {
12554        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12555    }
12556
12557    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12558        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12559    }
12560
12561    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12562        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12563    }
12564
12565    private static boolean isSystemApp(PackageSetting ps) {
12566        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12567    }
12568
12569    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12570        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12571    }
12572
12573    private int packageFlagsToInstallFlags(PackageSetting ps) {
12574        int installFlags = 0;
12575        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12576            // This existing package was an external ASEC install when we have
12577            // the external flag without a UUID
12578            installFlags |= PackageManager.INSTALL_EXTERNAL;
12579        }
12580        if (ps.isForwardLocked()) {
12581            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12582        }
12583        return installFlags;
12584    }
12585
12586    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12587        if (isExternal(pkg)) {
12588            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12589                return mSettings.getExternalVersion();
12590            } else {
12591                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12592            }
12593        } else {
12594            return mSettings.getInternalVersion();
12595        }
12596    }
12597
12598    private void deleteTempPackageFiles() {
12599        final FilenameFilter filter = new FilenameFilter() {
12600            public boolean accept(File dir, String name) {
12601                return name.startsWith("vmdl") && name.endsWith(".tmp");
12602            }
12603        };
12604        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12605            file.delete();
12606        }
12607    }
12608
12609    @Override
12610    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12611            int flags) {
12612        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12613                flags);
12614    }
12615
12616    @Override
12617    public void deletePackage(final String packageName,
12618            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12619        mContext.enforceCallingOrSelfPermission(
12620                android.Manifest.permission.DELETE_PACKAGES, null);
12621        Preconditions.checkNotNull(packageName);
12622        Preconditions.checkNotNull(observer);
12623        final int uid = Binder.getCallingUid();
12624        if (UserHandle.getUserId(uid) != userId) {
12625            mContext.enforceCallingPermission(
12626                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12627                    "deletePackage for user " + userId);
12628        }
12629        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12630            try {
12631                observer.onPackageDeleted(packageName,
12632                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12633            } catch (RemoteException re) {
12634            }
12635            return;
12636        }
12637
12638        boolean uninstallBlocked = false;
12639        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12640            int[] users = sUserManager.getUserIds();
12641            for (int i = 0; i < users.length; ++i) {
12642                if (getBlockUninstallForUser(packageName, users[i])) {
12643                    uninstallBlocked = true;
12644                    break;
12645                }
12646            }
12647        } else {
12648            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12649        }
12650        if (uninstallBlocked) {
12651            try {
12652                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12653                        null);
12654            } catch (RemoteException re) {
12655            }
12656            return;
12657        }
12658
12659        if (DEBUG_REMOVE) {
12660            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12661        }
12662        // Queue up an async operation since the package deletion may take a little while.
12663        mHandler.post(new Runnable() {
12664            public void run() {
12665                mHandler.removeCallbacks(this);
12666                final int returnCode = deletePackageX(packageName, userId, flags);
12667                if (observer != null) {
12668                    try {
12669                        observer.onPackageDeleted(packageName, returnCode, null);
12670                    } catch (RemoteException e) {
12671                        Log.i(TAG, "Observer no longer exists.");
12672                    } //end catch
12673                } //end if
12674            } //end run
12675        });
12676    }
12677
12678    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12679        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12680                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12681        try {
12682            if (dpm != null) {
12683                if (dpm.isDeviceOwner(packageName)) {
12684                    return true;
12685                }
12686                int[] users;
12687                if (userId == UserHandle.USER_ALL) {
12688                    users = sUserManager.getUserIds();
12689                } else {
12690                    users = new int[]{userId};
12691                }
12692                for (int i = 0; i < users.length; ++i) {
12693                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12694                        return true;
12695                    }
12696                }
12697            }
12698        } catch (RemoteException e) {
12699        }
12700        return false;
12701    }
12702
12703    /**
12704     *  This method is an internal method that could be get invoked either
12705     *  to delete an installed package or to clean up a failed installation.
12706     *  After deleting an installed package, a broadcast is sent to notify any
12707     *  listeners that the package has been installed. For cleaning up a failed
12708     *  installation, the broadcast is not necessary since the package's
12709     *  installation wouldn't have sent the initial broadcast either
12710     *  The key steps in deleting a package are
12711     *  deleting the package information in internal structures like mPackages,
12712     *  deleting the packages base directories through installd
12713     *  updating mSettings to reflect current status
12714     *  persisting settings for later use
12715     *  sending a broadcast if necessary
12716     */
12717    private int deletePackageX(String packageName, int userId, int flags) {
12718        final PackageRemovedInfo info = new PackageRemovedInfo();
12719        final boolean res;
12720
12721        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12722                ? UserHandle.ALL : new UserHandle(userId);
12723
12724        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12725            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12726            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12727        }
12728
12729        boolean removedForAllUsers = false;
12730        boolean systemUpdate = false;
12731
12732        // for the uninstall-updates case and restricted profiles, remember the per-
12733        // userhandle installed state
12734        int[] allUsers;
12735        boolean[] perUserInstalled;
12736        synchronized (mPackages) {
12737            PackageSetting ps = mSettings.mPackages.get(packageName);
12738            allUsers = sUserManager.getUserIds();
12739            perUserInstalled = new boolean[allUsers.length];
12740            for (int i = 0; i < allUsers.length; i++) {
12741                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12742            }
12743        }
12744
12745        synchronized (mInstallLock) {
12746            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12747            res = deletePackageLI(packageName, removeForUser,
12748                    true, allUsers, perUserInstalled,
12749                    flags | REMOVE_CHATTY, info, true);
12750            systemUpdate = info.isRemovedPackageSystemUpdate;
12751            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12752                removedForAllUsers = true;
12753            }
12754            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12755                    + " removedForAllUsers=" + removedForAllUsers);
12756        }
12757
12758        if (res) {
12759            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12760
12761            // If the removed package was a system update, the old system package
12762            // was re-enabled; we need to broadcast this information
12763            if (systemUpdate) {
12764                Bundle extras = new Bundle(1);
12765                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12766                        ? info.removedAppId : info.uid);
12767                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12768
12769                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12770                        extras, null, null, null);
12771                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12772                        extras, null, null, null);
12773                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12774                        null, packageName, null, null);
12775            }
12776        }
12777        // Force a gc here.
12778        Runtime.getRuntime().gc();
12779        // Delete the resources here after sending the broadcast to let
12780        // other processes clean up before deleting resources.
12781        if (info.args != null) {
12782            synchronized (mInstallLock) {
12783                info.args.doPostDeleteLI(true);
12784            }
12785        }
12786
12787        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12788    }
12789
12790    class PackageRemovedInfo {
12791        String removedPackage;
12792        int uid = -1;
12793        int removedAppId = -1;
12794        int[] removedUsers = null;
12795        boolean isRemovedPackageSystemUpdate = false;
12796        // Clean up resources deleted packages.
12797        InstallArgs args = null;
12798
12799        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12800            Bundle extras = new Bundle(1);
12801            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12802            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12803            if (replacing) {
12804                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12805            }
12806            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12807            if (removedPackage != null) {
12808                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12809                        extras, null, null, removedUsers);
12810                if (fullRemove && !replacing) {
12811                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12812                            extras, null, null, removedUsers);
12813                }
12814            }
12815            if (removedAppId >= 0) {
12816                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12817                        removedUsers);
12818            }
12819        }
12820    }
12821
12822    /*
12823     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12824     * flag is not set, the data directory is removed as well.
12825     * make sure this flag is set for partially installed apps. If not its meaningless to
12826     * delete a partially installed application.
12827     */
12828    private void removePackageDataLI(PackageSetting ps,
12829            int[] allUserHandles, boolean[] perUserInstalled,
12830            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12831        String packageName = ps.name;
12832        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12833        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12834        // Retrieve object to delete permissions for shared user later on
12835        final PackageSetting deletedPs;
12836        // reader
12837        synchronized (mPackages) {
12838            deletedPs = mSettings.mPackages.get(packageName);
12839            if (outInfo != null) {
12840                outInfo.removedPackage = packageName;
12841                outInfo.removedUsers = deletedPs != null
12842                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12843                        : null;
12844            }
12845        }
12846        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12847            removeDataDirsLI(ps.volumeUuid, packageName);
12848            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12849        }
12850        // writer
12851        synchronized (mPackages) {
12852            if (deletedPs != null) {
12853                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12854                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12855                    clearDefaultBrowserIfNeeded(packageName);
12856                    if (outInfo != null) {
12857                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12858                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12859                    }
12860                    updatePermissionsLPw(deletedPs.name, null, 0);
12861                    if (deletedPs.sharedUser != null) {
12862                        // Remove permissions associated with package. Since runtime
12863                        // permissions are per user we have to kill the removed package
12864                        // or packages running under the shared user of the removed
12865                        // package if revoking the permissions requested only by the removed
12866                        // package is successful and this causes a change in gids.
12867                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12868                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12869                                    userId);
12870                            if (userIdToKill == UserHandle.USER_ALL
12871                                    || userIdToKill >= UserHandle.USER_OWNER) {
12872                                // If gids changed for this user, kill all affected packages.
12873                                mHandler.post(new Runnable() {
12874                                    @Override
12875                                    public void run() {
12876                                        // This has to happen with no lock held.
12877                                        killApplication(deletedPs.name, deletedPs.appId,
12878                                                KILL_APP_REASON_GIDS_CHANGED);
12879                                    }
12880                                });
12881                                break;
12882                            }
12883                        }
12884                    }
12885                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12886                }
12887                // make sure to preserve per-user disabled state if this removal was just
12888                // a downgrade of a system app to the factory package
12889                if (allUserHandles != null && perUserInstalled != null) {
12890                    if (DEBUG_REMOVE) {
12891                        Slog.d(TAG, "Propagating install state across downgrade");
12892                    }
12893                    for (int i = 0; i < allUserHandles.length; i++) {
12894                        if (DEBUG_REMOVE) {
12895                            Slog.d(TAG, "    user " + allUserHandles[i]
12896                                    + " => " + perUserInstalled[i]);
12897                        }
12898                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12899                    }
12900                }
12901            }
12902            // can downgrade to reader
12903            if (writeSettings) {
12904                // Save settings now
12905                mSettings.writeLPr();
12906            }
12907        }
12908        if (outInfo != null) {
12909            // A user ID was deleted here. Go through all users and remove it
12910            // from KeyStore.
12911            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12912        }
12913    }
12914
12915    static boolean locationIsPrivileged(File path) {
12916        try {
12917            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12918                    .getCanonicalPath();
12919            return path.getCanonicalPath().startsWith(privilegedAppDir);
12920        } catch (IOException e) {
12921            Slog.e(TAG, "Unable to access code path " + path);
12922        }
12923        return false;
12924    }
12925
12926    /*
12927     * Tries to delete system package.
12928     */
12929    private boolean deleteSystemPackageLI(PackageSetting newPs,
12930            int[] allUserHandles, boolean[] perUserInstalled,
12931            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12932        final boolean applyUserRestrictions
12933                = (allUserHandles != null) && (perUserInstalled != null);
12934        PackageSetting disabledPs = null;
12935        // Confirm if the system package has been updated
12936        // An updated system app can be deleted. This will also have to restore
12937        // the system pkg from system partition
12938        // reader
12939        synchronized (mPackages) {
12940            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12941        }
12942        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12943                + " disabledPs=" + disabledPs);
12944        if (disabledPs == null) {
12945            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12946            return false;
12947        } else if (DEBUG_REMOVE) {
12948            Slog.d(TAG, "Deleting system pkg from data partition");
12949        }
12950        if (DEBUG_REMOVE) {
12951            if (applyUserRestrictions) {
12952                Slog.d(TAG, "Remembering install states:");
12953                for (int i = 0; i < allUserHandles.length; i++) {
12954                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12955                }
12956            }
12957        }
12958        // Delete the updated package
12959        outInfo.isRemovedPackageSystemUpdate = true;
12960        if (disabledPs.versionCode < newPs.versionCode) {
12961            // Delete data for downgrades
12962            flags &= ~PackageManager.DELETE_KEEP_DATA;
12963        } else {
12964            // Preserve data by setting flag
12965            flags |= PackageManager.DELETE_KEEP_DATA;
12966        }
12967        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12968                allUserHandles, perUserInstalled, outInfo, writeSettings);
12969        if (!ret) {
12970            return false;
12971        }
12972        // writer
12973        synchronized (mPackages) {
12974            // Reinstate the old system package
12975            mSettings.enableSystemPackageLPw(newPs.name);
12976            // Remove any native libraries from the upgraded package.
12977            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12978        }
12979        // Install the system package
12980        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12981        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12982        if (locationIsPrivileged(disabledPs.codePath)) {
12983            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12984        }
12985
12986        final PackageParser.Package newPkg;
12987        try {
12988            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12989        } catch (PackageManagerException e) {
12990            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12991            return false;
12992        }
12993
12994        // writer
12995        synchronized (mPackages) {
12996            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12997
12998            // Propagate the permissions state as we do not want to drop on the floor
12999            // runtime permissions. The update permissions method below will take
13000            // care of removing obsolete permissions and grant install permissions.
13001            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13002            updatePermissionsLPw(newPkg.packageName, newPkg,
13003                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13004
13005            if (applyUserRestrictions) {
13006                if (DEBUG_REMOVE) {
13007                    Slog.d(TAG, "Propagating install state across reinstall");
13008                }
13009                for (int i = 0; i < allUserHandles.length; i++) {
13010                    if (DEBUG_REMOVE) {
13011                        Slog.d(TAG, "    user " + allUserHandles[i]
13012                                + " => " + perUserInstalled[i]);
13013                    }
13014                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13015
13016                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13017                }
13018                // Regardless of writeSettings we need to ensure that this restriction
13019                // state propagation is persisted
13020                mSettings.writeAllUsersPackageRestrictionsLPr();
13021            }
13022            // can downgrade to reader here
13023            if (writeSettings) {
13024                mSettings.writeLPr();
13025            }
13026        }
13027        return true;
13028    }
13029
13030    private boolean deleteInstalledPackageLI(PackageSetting ps,
13031            boolean deleteCodeAndResources, int flags,
13032            int[] allUserHandles, boolean[] perUserInstalled,
13033            PackageRemovedInfo outInfo, boolean writeSettings) {
13034        if (outInfo != null) {
13035            outInfo.uid = ps.appId;
13036        }
13037
13038        // Delete package data from internal structures and also remove data if flag is set
13039        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13040
13041        // Delete application code and resources
13042        if (deleteCodeAndResources && (outInfo != null)) {
13043            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13044                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13045            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13046        }
13047        return true;
13048    }
13049
13050    @Override
13051    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13052            int userId) {
13053        mContext.enforceCallingOrSelfPermission(
13054                android.Manifest.permission.DELETE_PACKAGES, null);
13055        synchronized (mPackages) {
13056            PackageSetting ps = mSettings.mPackages.get(packageName);
13057            if (ps == null) {
13058                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13059                return false;
13060            }
13061            if (!ps.getInstalled(userId)) {
13062                // Can't block uninstall for an app that is not installed or enabled.
13063                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13064                return false;
13065            }
13066            ps.setBlockUninstall(blockUninstall, userId);
13067            mSettings.writePackageRestrictionsLPr(userId);
13068        }
13069        return true;
13070    }
13071
13072    @Override
13073    public boolean getBlockUninstallForUser(String packageName, int userId) {
13074        synchronized (mPackages) {
13075            PackageSetting ps = mSettings.mPackages.get(packageName);
13076            if (ps == null) {
13077                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13078                return false;
13079            }
13080            return ps.getBlockUninstall(userId);
13081        }
13082    }
13083
13084    /*
13085     * This method handles package deletion in general
13086     */
13087    private boolean deletePackageLI(String packageName, UserHandle user,
13088            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13089            int flags, PackageRemovedInfo outInfo,
13090            boolean writeSettings) {
13091        if (packageName == null) {
13092            Slog.w(TAG, "Attempt to delete null packageName.");
13093            return false;
13094        }
13095        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13096        PackageSetting ps;
13097        boolean dataOnly = false;
13098        int removeUser = -1;
13099        int appId = -1;
13100        synchronized (mPackages) {
13101            ps = mSettings.mPackages.get(packageName);
13102            if (ps == null) {
13103                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13104                return false;
13105            }
13106            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13107                    && user.getIdentifier() != UserHandle.USER_ALL) {
13108                // The caller is asking that the package only be deleted for a single
13109                // user.  To do this, we just mark its uninstalled state and delete
13110                // its data.  If this is a system app, we only allow this to happen if
13111                // they have set the special DELETE_SYSTEM_APP which requests different
13112                // semantics than normal for uninstalling system apps.
13113                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13114                final int userId = user.getIdentifier();
13115                ps.setUserState(userId,
13116                        COMPONENT_ENABLED_STATE_DEFAULT,
13117                        false, //installed
13118                        true,  //stopped
13119                        true,  //notLaunched
13120                        false, //hidden
13121                        null, null, null,
13122                        false, // blockUninstall
13123                        ps.readUserState(userId).domainVerificationStatus, 0);
13124                if (!isSystemApp(ps)) {
13125                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13126                        // Other user still have this package installed, so all
13127                        // we need to do is clear this user's data and save that
13128                        // it is uninstalled.
13129                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13130                        removeUser = user.getIdentifier();
13131                        appId = ps.appId;
13132                        scheduleWritePackageRestrictionsLocked(removeUser);
13133                    } else {
13134                        // We need to set it back to 'installed' so the uninstall
13135                        // broadcasts will be sent correctly.
13136                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13137                        ps.setInstalled(true, user.getIdentifier());
13138                    }
13139                } else {
13140                    // This is a system app, so we assume that the
13141                    // other users still have this package installed, so all
13142                    // we need to do is clear this user's data and save that
13143                    // it is uninstalled.
13144                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13145                    removeUser = user.getIdentifier();
13146                    appId = ps.appId;
13147                    scheduleWritePackageRestrictionsLocked(removeUser);
13148                }
13149            }
13150        }
13151
13152        if (removeUser >= 0) {
13153            // From above, we determined that we are deleting this only
13154            // for a single user.  Continue the work here.
13155            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13156            if (outInfo != null) {
13157                outInfo.removedPackage = packageName;
13158                outInfo.removedAppId = appId;
13159                outInfo.removedUsers = new int[] {removeUser};
13160            }
13161            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13162            removeKeystoreDataIfNeeded(removeUser, appId);
13163            schedulePackageCleaning(packageName, removeUser, false);
13164            synchronized (mPackages) {
13165                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13166                    scheduleWritePackageRestrictionsLocked(removeUser);
13167                }
13168                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13169            }
13170            return true;
13171        }
13172
13173        if (dataOnly) {
13174            // Delete application data first
13175            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13176            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13177            return true;
13178        }
13179
13180        boolean ret = false;
13181        if (isSystemApp(ps)) {
13182            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13183            // When an updated system application is deleted we delete the existing resources as well and
13184            // fall back to existing code in system partition
13185            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13186                    flags, outInfo, writeSettings);
13187        } else {
13188            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13189            // Kill application pre-emptively especially for apps on sd.
13190            killApplication(packageName, ps.appId, "uninstall pkg");
13191            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13192                    allUserHandles, perUserInstalled,
13193                    outInfo, writeSettings);
13194        }
13195
13196        return ret;
13197    }
13198
13199    private final class ClearStorageConnection implements ServiceConnection {
13200        IMediaContainerService mContainerService;
13201
13202        @Override
13203        public void onServiceConnected(ComponentName name, IBinder service) {
13204            synchronized (this) {
13205                mContainerService = IMediaContainerService.Stub.asInterface(service);
13206                notifyAll();
13207            }
13208        }
13209
13210        @Override
13211        public void onServiceDisconnected(ComponentName name) {
13212        }
13213    }
13214
13215    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13216        final boolean mounted;
13217        if (Environment.isExternalStorageEmulated()) {
13218            mounted = true;
13219        } else {
13220            final String status = Environment.getExternalStorageState();
13221
13222            mounted = status.equals(Environment.MEDIA_MOUNTED)
13223                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13224        }
13225
13226        if (!mounted) {
13227            return;
13228        }
13229
13230        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13231        int[] users;
13232        if (userId == UserHandle.USER_ALL) {
13233            users = sUserManager.getUserIds();
13234        } else {
13235            users = new int[] { userId };
13236        }
13237        final ClearStorageConnection conn = new ClearStorageConnection();
13238        if (mContext.bindServiceAsUser(
13239                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13240            try {
13241                for (int curUser : users) {
13242                    long timeout = SystemClock.uptimeMillis() + 5000;
13243                    synchronized (conn) {
13244                        long now = SystemClock.uptimeMillis();
13245                        while (conn.mContainerService == null && now < timeout) {
13246                            try {
13247                                conn.wait(timeout - now);
13248                            } catch (InterruptedException e) {
13249                            }
13250                        }
13251                    }
13252                    if (conn.mContainerService == null) {
13253                        return;
13254                    }
13255
13256                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13257                    clearDirectory(conn.mContainerService,
13258                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13259                    if (allData) {
13260                        clearDirectory(conn.mContainerService,
13261                                userEnv.buildExternalStorageAppDataDirs(packageName));
13262                        clearDirectory(conn.mContainerService,
13263                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13264                    }
13265                }
13266            } finally {
13267                mContext.unbindService(conn);
13268            }
13269        }
13270    }
13271
13272    @Override
13273    public void clearApplicationUserData(final String packageName,
13274            final IPackageDataObserver observer, final int userId) {
13275        mContext.enforceCallingOrSelfPermission(
13276                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13277        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13278        // Queue up an async operation since the package deletion may take a little while.
13279        mHandler.post(new Runnable() {
13280            public void run() {
13281                mHandler.removeCallbacks(this);
13282                final boolean succeeded;
13283                synchronized (mInstallLock) {
13284                    succeeded = clearApplicationUserDataLI(packageName, userId);
13285                }
13286                clearExternalStorageDataSync(packageName, userId, true);
13287                if (succeeded) {
13288                    // invoke DeviceStorageMonitor's update method to clear any notifications
13289                    DeviceStorageMonitorInternal
13290                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13291                    if (dsm != null) {
13292                        dsm.checkMemory();
13293                    }
13294                }
13295                if(observer != null) {
13296                    try {
13297                        observer.onRemoveCompleted(packageName, succeeded);
13298                    } catch (RemoteException e) {
13299                        Log.i(TAG, "Observer no longer exists.");
13300                    }
13301                } //end if observer
13302            } //end run
13303        });
13304    }
13305
13306    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13307        if (packageName == null) {
13308            Slog.w(TAG, "Attempt to delete null packageName.");
13309            return false;
13310        }
13311
13312        // Try finding details about the requested package
13313        PackageParser.Package pkg;
13314        synchronized (mPackages) {
13315            pkg = mPackages.get(packageName);
13316            if (pkg == null) {
13317                final PackageSetting ps = mSettings.mPackages.get(packageName);
13318                if (ps != null) {
13319                    pkg = ps.pkg;
13320                }
13321            }
13322
13323            if (pkg == null) {
13324                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13325                return false;
13326            }
13327
13328            PackageSetting ps = (PackageSetting) pkg.mExtras;
13329            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13330        }
13331
13332        // Always delete data directories for package, even if we found no other
13333        // record of app. This helps users recover from UID mismatches without
13334        // resorting to a full data wipe.
13335        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13336        if (retCode < 0) {
13337            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13338            return false;
13339        }
13340
13341        final int appId = pkg.applicationInfo.uid;
13342        removeKeystoreDataIfNeeded(userId, appId);
13343
13344        // Create a native library symlink only if we have native libraries
13345        // and if the native libraries are 32 bit libraries. We do not provide
13346        // this symlink for 64 bit libraries.
13347        if (pkg.applicationInfo.primaryCpuAbi != null &&
13348                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13349            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13350            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13351                    nativeLibPath, userId) < 0) {
13352                Slog.w(TAG, "Failed linking native library dir");
13353                return false;
13354            }
13355        }
13356
13357        return true;
13358    }
13359
13360    /**
13361     * Reverts user permission state changes (permissions and flags) in
13362     * all packages for a given user.
13363     *
13364     * @param userId The device user for which to do a reset.
13365     */
13366    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13367        final int packageCount = mPackages.size();
13368        for (int i = 0; i < packageCount; i++) {
13369            PackageParser.Package pkg = mPackages.valueAt(i);
13370            PackageSetting ps = (PackageSetting) pkg.mExtras;
13371            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13372        }
13373    }
13374
13375    /**
13376     * Reverts user permission state changes (permissions and flags).
13377     *
13378     * @param ps The package for which to reset.
13379     * @param userId The device user for which to do a reset.
13380     */
13381    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13382            final PackageSetting ps, final int userId) {
13383        if (ps.pkg == null) {
13384            return;
13385        }
13386
13387        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13388                | FLAG_PERMISSION_USER_FIXED
13389                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13390
13391        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13392                | FLAG_PERMISSION_POLICY_FIXED;
13393
13394        boolean writeInstallPermissions = false;
13395        boolean writeRuntimePermissions = false;
13396
13397        final int permissionCount = ps.pkg.requestedPermissions.size();
13398        for (int i = 0; i < permissionCount; i++) {
13399            String permission = ps.pkg.requestedPermissions.get(i);
13400
13401            BasePermission bp = mSettings.mPermissions.get(permission);
13402            if (bp == null) {
13403                continue;
13404            }
13405
13406            // If shared user we just reset the state to which only this app contributed.
13407            if (ps.sharedUser != null) {
13408                boolean used = false;
13409                final int packageCount = ps.sharedUser.packages.size();
13410                for (int j = 0; j < packageCount; j++) {
13411                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13412                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13413                            && pkg.pkg.requestedPermissions.contains(permission)) {
13414                        used = true;
13415                        break;
13416                    }
13417                }
13418                if (used) {
13419                    continue;
13420                }
13421            }
13422
13423            PermissionsState permissionsState = ps.getPermissionsState();
13424
13425            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13426
13427            // Always clear the user settable flags.
13428            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13429                    bp.name) != null;
13430            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13431                if (hasInstallState) {
13432                    writeInstallPermissions = true;
13433                } else {
13434                    writeRuntimePermissions = true;
13435                }
13436            }
13437
13438            // Below is only runtime permission handling.
13439            if (!bp.isRuntime()) {
13440                continue;
13441            }
13442
13443            // Never clobber system or policy.
13444            if ((oldFlags & policyOrSystemFlags) != 0) {
13445                continue;
13446            }
13447
13448            // If this permission was granted by default, make sure it is.
13449            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13450                if (permissionsState.grantRuntimePermission(bp, userId)
13451                        != PERMISSION_OPERATION_FAILURE) {
13452                    writeRuntimePermissions = true;
13453                }
13454            } else {
13455                // Otherwise, reset the permission.
13456                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13457                switch (revokeResult) {
13458                    case PERMISSION_OPERATION_SUCCESS: {
13459                        writeRuntimePermissions = true;
13460                    } break;
13461
13462                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13463                        writeRuntimePermissions = true;
13464                        final int appId = ps.appId;
13465                        mHandler.post(new Runnable() {
13466                            @Override
13467                            public void run() {
13468                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13469                            }
13470                        });
13471                    } break;
13472                }
13473            }
13474        }
13475
13476        // Synchronously write as we are taking permissions away.
13477        if (writeRuntimePermissions) {
13478            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13479        }
13480
13481        // Synchronously write as we are taking permissions away.
13482        if (writeInstallPermissions) {
13483            mSettings.writeLPr();
13484        }
13485    }
13486
13487    /**
13488     * Remove entries from the keystore daemon. Will only remove it if the
13489     * {@code appId} is valid.
13490     */
13491    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13492        if (appId < 0) {
13493            return;
13494        }
13495
13496        final KeyStore keyStore = KeyStore.getInstance();
13497        if (keyStore != null) {
13498            if (userId == UserHandle.USER_ALL) {
13499                for (final int individual : sUserManager.getUserIds()) {
13500                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13501                }
13502            } else {
13503                keyStore.clearUid(UserHandle.getUid(userId, appId));
13504            }
13505        } else {
13506            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13507        }
13508    }
13509
13510    @Override
13511    public void deleteApplicationCacheFiles(final String packageName,
13512            final IPackageDataObserver observer) {
13513        mContext.enforceCallingOrSelfPermission(
13514                android.Manifest.permission.DELETE_CACHE_FILES, null);
13515        // Queue up an async operation since the package deletion may take a little while.
13516        final int userId = UserHandle.getCallingUserId();
13517        mHandler.post(new Runnable() {
13518            public void run() {
13519                mHandler.removeCallbacks(this);
13520                final boolean succeded;
13521                synchronized (mInstallLock) {
13522                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13523                }
13524                clearExternalStorageDataSync(packageName, userId, false);
13525                if (observer != null) {
13526                    try {
13527                        observer.onRemoveCompleted(packageName, succeded);
13528                    } catch (RemoteException e) {
13529                        Log.i(TAG, "Observer no longer exists.");
13530                    }
13531                } //end if observer
13532            } //end run
13533        });
13534    }
13535
13536    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13537        if (packageName == null) {
13538            Slog.w(TAG, "Attempt to delete null packageName.");
13539            return false;
13540        }
13541        PackageParser.Package p;
13542        synchronized (mPackages) {
13543            p = mPackages.get(packageName);
13544        }
13545        if (p == null) {
13546            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13547            return false;
13548        }
13549        final ApplicationInfo applicationInfo = p.applicationInfo;
13550        if (applicationInfo == null) {
13551            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13552            return false;
13553        }
13554        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13555        if (retCode < 0) {
13556            Slog.w(TAG, "Couldn't remove cache files for package: "
13557                       + packageName + " u" + userId);
13558            return false;
13559        }
13560        return true;
13561    }
13562
13563    @Override
13564    public void getPackageSizeInfo(final String packageName, int userHandle,
13565            final IPackageStatsObserver observer) {
13566        mContext.enforceCallingOrSelfPermission(
13567                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13568        if (packageName == null) {
13569            throw new IllegalArgumentException("Attempt to get size of null packageName");
13570        }
13571
13572        PackageStats stats = new PackageStats(packageName, userHandle);
13573
13574        /*
13575         * Queue up an async operation since the package measurement may take a
13576         * little while.
13577         */
13578        Message msg = mHandler.obtainMessage(INIT_COPY);
13579        msg.obj = new MeasureParams(stats, observer);
13580        mHandler.sendMessage(msg);
13581    }
13582
13583    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13584            PackageStats pStats) {
13585        if (packageName == null) {
13586            Slog.w(TAG, "Attempt to get size of null packageName.");
13587            return false;
13588        }
13589        PackageParser.Package p;
13590        boolean dataOnly = false;
13591        String libDirRoot = null;
13592        String asecPath = null;
13593        PackageSetting ps = null;
13594        synchronized (mPackages) {
13595            p = mPackages.get(packageName);
13596            ps = mSettings.mPackages.get(packageName);
13597            if(p == null) {
13598                dataOnly = true;
13599                if((ps == null) || (ps.pkg == null)) {
13600                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13601                    return false;
13602                }
13603                p = ps.pkg;
13604            }
13605            if (ps != null) {
13606                libDirRoot = ps.legacyNativeLibraryPathString;
13607            }
13608            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13609                final long token = Binder.clearCallingIdentity();
13610                try {
13611                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13612                    if (secureContainerId != null) {
13613                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13614                    }
13615                } finally {
13616                    Binder.restoreCallingIdentity(token);
13617                }
13618            }
13619        }
13620        String publicSrcDir = null;
13621        if(!dataOnly) {
13622            final ApplicationInfo applicationInfo = p.applicationInfo;
13623            if (applicationInfo == null) {
13624                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13625                return false;
13626            }
13627            if (p.isForwardLocked()) {
13628                publicSrcDir = applicationInfo.getBaseResourcePath();
13629            }
13630        }
13631        // TODO: extend to measure size of split APKs
13632        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13633        // not just the first level.
13634        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13635        // just the primary.
13636        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13637        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13638                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13639        if (res < 0) {
13640            return false;
13641        }
13642
13643        // Fix-up for forward-locked applications in ASEC containers.
13644        if (!isExternal(p)) {
13645            pStats.codeSize += pStats.externalCodeSize;
13646            pStats.externalCodeSize = 0L;
13647        }
13648
13649        return true;
13650    }
13651
13652
13653    @Override
13654    public void addPackageToPreferred(String packageName) {
13655        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13656    }
13657
13658    @Override
13659    public void removePackageFromPreferred(String packageName) {
13660        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13661    }
13662
13663    @Override
13664    public List<PackageInfo> getPreferredPackages(int flags) {
13665        return new ArrayList<PackageInfo>();
13666    }
13667
13668    private int getUidTargetSdkVersionLockedLPr(int uid) {
13669        Object obj = mSettings.getUserIdLPr(uid);
13670        if (obj instanceof SharedUserSetting) {
13671            final SharedUserSetting sus = (SharedUserSetting) obj;
13672            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13673            final Iterator<PackageSetting> it = sus.packages.iterator();
13674            while (it.hasNext()) {
13675                final PackageSetting ps = it.next();
13676                if (ps.pkg != null) {
13677                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13678                    if (v < vers) vers = v;
13679                }
13680            }
13681            return vers;
13682        } else if (obj instanceof PackageSetting) {
13683            final PackageSetting ps = (PackageSetting) obj;
13684            if (ps.pkg != null) {
13685                return ps.pkg.applicationInfo.targetSdkVersion;
13686            }
13687        }
13688        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13689    }
13690
13691    @Override
13692    public void addPreferredActivity(IntentFilter filter, int match,
13693            ComponentName[] set, ComponentName activity, int userId) {
13694        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13695                "Adding preferred");
13696    }
13697
13698    private void addPreferredActivityInternal(IntentFilter filter, int match,
13699            ComponentName[] set, ComponentName activity, boolean always, int userId,
13700            String opname) {
13701        // writer
13702        int callingUid = Binder.getCallingUid();
13703        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13704        if (filter.countActions() == 0) {
13705            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13706            return;
13707        }
13708        synchronized (mPackages) {
13709            if (mContext.checkCallingOrSelfPermission(
13710                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13711                    != PackageManager.PERMISSION_GRANTED) {
13712                if (getUidTargetSdkVersionLockedLPr(callingUid)
13713                        < Build.VERSION_CODES.FROYO) {
13714                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13715                            + callingUid);
13716                    return;
13717                }
13718                mContext.enforceCallingOrSelfPermission(
13719                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13720            }
13721
13722            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13723            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13724                    + userId + ":");
13725            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13726            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13727            scheduleWritePackageRestrictionsLocked(userId);
13728        }
13729    }
13730
13731    @Override
13732    public void replacePreferredActivity(IntentFilter filter, int match,
13733            ComponentName[] set, ComponentName activity, int userId) {
13734        if (filter.countActions() != 1) {
13735            throw new IllegalArgumentException(
13736                    "replacePreferredActivity expects filter to have only 1 action.");
13737        }
13738        if (filter.countDataAuthorities() != 0
13739                || filter.countDataPaths() != 0
13740                || filter.countDataSchemes() > 1
13741                || filter.countDataTypes() != 0) {
13742            throw new IllegalArgumentException(
13743                    "replacePreferredActivity expects filter to have no data authorities, " +
13744                    "paths, or types; and at most one scheme.");
13745        }
13746
13747        final int callingUid = Binder.getCallingUid();
13748        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13749        synchronized (mPackages) {
13750            if (mContext.checkCallingOrSelfPermission(
13751                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13752                    != PackageManager.PERMISSION_GRANTED) {
13753                if (getUidTargetSdkVersionLockedLPr(callingUid)
13754                        < Build.VERSION_CODES.FROYO) {
13755                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13756                            + Binder.getCallingUid());
13757                    return;
13758                }
13759                mContext.enforceCallingOrSelfPermission(
13760                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13761            }
13762
13763            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13764            if (pir != null) {
13765                // Get all of the existing entries that exactly match this filter.
13766                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13767                if (existing != null && existing.size() == 1) {
13768                    PreferredActivity cur = existing.get(0);
13769                    if (DEBUG_PREFERRED) {
13770                        Slog.i(TAG, "Checking replace of preferred:");
13771                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13772                        if (!cur.mPref.mAlways) {
13773                            Slog.i(TAG, "  -- CUR; not mAlways!");
13774                        } else {
13775                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13776                            Slog.i(TAG, "  -- CUR: mSet="
13777                                    + Arrays.toString(cur.mPref.mSetComponents));
13778                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13779                            Slog.i(TAG, "  -- NEW: mMatch="
13780                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13781                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13782                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13783                        }
13784                    }
13785                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13786                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13787                            && cur.mPref.sameSet(set)) {
13788                        // Setting the preferred activity to what it happens to be already
13789                        if (DEBUG_PREFERRED) {
13790                            Slog.i(TAG, "Replacing with same preferred activity "
13791                                    + cur.mPref.mShortComponent + " for user "
13792                                    + userId + ":");
13793                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13794                        }
13795                        return;
13796                    }
13797                }
13798
13799                if (existing != null) {
13800                    if (DEBUG_PREFERRED) {
13801                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13802                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13803                    }
13804                    for (int i = 0; i < existing.size(); i++) {
13805                        PreferredActivity pa = existing.get(i);
13806                        if (DEBUG_PREFERRED) {
13807                            Slog.i(TAG, "Removing existing preferred activity "
13808                                    + pa.mPref.mComponent + ":");
13809                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13810                        }
13811                        pir.removeFilter(pa);
13812                    }
13813                }
13814            }
13815            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13816                    "Replacing preferred");
13817        }
13818    }
13819
13820    @Override
13821    public void clearPackagePreferredActivities(String packageName) {
13822        final int uid = Binder.getCallingUid();
13823        // writer
13824        synchronized (mPackages) {
13825            PackageParser.Package pkg = mPackages.get(packageName);
13826            if (pkg == null || pkg.applicationInfo.uid != uid) {
13827                if (mContext.checkCallingOrSelfPermission(
13828                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13829                        != PackageManager.PERMISSION_GRANTED) {
13830                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13831                            < Build.VERSION_CODES.FROYO) {
13832                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13833                                + Binder.getCallingUid());
13834                        return;
13835                    }
13836                    mContext.enforceCallingOrSelfPermission(
13837                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13838                }
13839            }
13840
13841            int user = UserHandle.getCallingUserId();
13842            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13843                scheduleWritePackageRestrictionsLocked(user);
13844            }
13845        }
13846    }
13847
13848    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13849    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13850        ArrayList<PreferredActivity> removed = null;
13851        boolean changed = false;
13852        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13853            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13854            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13855            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13856                continue;
13857            }
13858            Iterator<PreferredActivity> it = pir.filterIterator();
13859            while (it.hasNext()) {
13860                PreferredActivity pa = it.next();
13861                // Mark entry for removal only if it matches the package name
13862                // and the entry is of type "always".
13863                if (packageName == null ||
13864                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13865                                && pa.mPref.mAlways)) {
13866                    if (removed == null) {
13867                        removed = new ArrayList<PreferredActivity>();
13868                    }
13869                    removed.add(pa);
13870                }
13871            }
13872            if (removed != null) {
13873                for (int j=0; j<removed.size(); j++) {
13874                    PreferredActivity pa = removed.get(j);
13875                    pir.removeFilter(pa);
13876                }
13877                changed = true;
13878            }
13879        }
13880        return changed;
13881    }
13882
13883    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13884    private void clearIntentFilterVerificationsLPw(int userId) {
13885        final int packageCount = mPackages.size();
13886        for (int i = 0; i < packageCount; i++) {
13887            PackageParser.Package pkg = mPackages.valueAt(i);
13888            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13889        }
13890    }
13891
13892    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13893    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13894        if (userId == UserHandle.USER_ALL) {
13895            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13896                    sUserManager.getUserIds())) {
13897                for (int oneUserId : sUserManager.getUserIds()) {
13898                    scheduleWritePackageRestrictionsLocked(oneUserId);
13899                }
13900            }
13901        } else {
13902            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13903                scheduleWritePackageRestrictionsLocked(userId);
13904            }
13905        }
13906    }
13907
13908    void clearDefaultBrowserIfNeeded(String packageName) {
13909        for (int oneUserId : sUserManager.getUserIds()) {
13910            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13911            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13912            if (packageName.equals(defaultBrowserPackageName)) {
13913                setDefaultBrowserPackageName(null, oneUserId);
13914            }
13915        }
13916    }
13917
13918    @Override
13919    public void resetApplicationPreferences(int userId) {
13920        mContext.enforceCallingOrSelfPermission(
13921                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13922        // writer
13923        synchronized (mPackages) {
13924            final long identity = Binder.clearCallingIdentity();
13925            try {
13926                clearPackagePreferredActivitiesLPw(null, userId);
13927                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13928                // TODO: We have to reset the default SMS and Phone. This requires
13929                // significant refactoring to keep all default apps in the package
13930                // manager (cleaner but more work) or have the services provide
13931                // callbacks to the package manager to request a default app reset.
13932                applyFactoryDefaultBrowserLPw(userId);
13933                clearIntentFilterVerificationsLPw(userId);
13934                primeDomainVerificationsLPw(userId);
13935                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13936                scheduleWritePackageRestrictionsLocked(userId);
13937            } finally {
13938                Binder.restoreCallingIdentity(identity);
13939            }
13940        }
13941    }
13942
13943    @Override
13944    public int getPreferredActivities(List<IntentFilter> outFilters,
13945            List<ComponentName> outActivities, String packageName) {
13946
13947        int num = 0;
13948        final int userId = UserHandle.getCallingUserId();
13949        // reader
13950        synchronized (mPackages) {
13951            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13952            if (pir != null) {
13953                final Iterator<PreferredActivity> it = pir.filterIterator();
13954                while (it.hasNext()) {
13955                    final PreferredActivity pa = it.next();
13956                    if (packageName == null
13957                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13958                                    && pa.mPref.mAlways)) {
13959                        if (outFilters != null) {
13960                            outFilters.add(new IntentFilter(pa));
13961                        }
13962                        if (outActivities != null) {
13963                            outActivities.add(pa.mPref.mComponent);
13964                        }
13965                    }
13966                }
13967            }
13968        }
13969
13970        return num;
13971    }
13972
13973    @Override
13974    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13975            int userId) {
13976        int callingUid = Binder.getCallingUid();
13977        if (callingUid != Process.SYSTEM_UID) {
13978            throw new SecurityException(
13979                    "addPersistentPreferredActivity can only be run by the system");
13980        }
13981        if (filter.countActions() == 0) {
13982            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13983            return;
13984        }
13985        synchronized (mPackages) {
13986            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13987                    " :");
13988            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13989            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13990                    new PersistentPreferredActivity(filter, activity));
13991            scheduleWritePackageRestrictionsLocked(userId);
13992        }
13993    }
13994
13995    @Override
13996    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13997        int callingUid = Binder.getCallingUid();
13998        if (callingUid != Process.SYSTEM_UID) {
13999            throw new SecurityException(
14000                    "clearPackagePersistentPreferredActivities can only be run by the system");
14001        }
14002        ArrayList<PersistentPreferredActivity> removed = null;
14003        boolean changed = false;
14004        synchronized (mPackages) {
14005            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14006                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14007                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14008                        .valueAt(i);
14009                if (userId != thisUserId) {
14010                    continue;
14011                }
14012                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14013                while (it.hasNext()) {
14014                    PersistentPreferredActivity ppa = it.next();
14015                    // Mark entry for removal only if it matches the package name.
14016                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14017                        if (removed == null) {
14018                            removed = new ArrayList<PersistentPreferredActivity>();
14019                        }
14020                        removed.add(ppa);
14021                    }
14022                }
14023                if (removed != null) {
14024                    for (int j=0; j<removed.size(); j++) {
14025                        PersistentPreferredActivity ppa = removed.get(j);
14026                        ppir.removeFilter(ppa);
14027                    }
14028                    changed = true;
14029                }
14030            }
14031
14032            if (changed) {
14033                scheduleWritePackageRestrictionsLocked(userId);
14034            }
14035        }
14036    }
14037
14038    /**
14039     * Common machinery for picking apart a restored XML blob and passing
14040     * it to a caller-supplied functor to be applied to the running system.
14041     */
14042    private void restoreFromXml(XmlPullParser parser, int userId,
14043            String expectedStartTag, BlobXmlRestorer functor)
14044            throws IOException, XmlPullParserException {
14045        int type;
14046        while ((type = parser.next()) != XmlPullParser.START_TAG
14047                && type != XmlPullParser.END_DOCUMENT) {
14048        }
14049        if (type != XmlPullParser.START_TAG) {
14050            // oops didn't find a start tag?!
14051            if (DEBUG_BACKUP) {
14052                Slog.e(TAG, "Didn't find start tag during restore");
14053            }
14054            return;
14055        }
14056
14057        // this is supposed to be TAG_PREFERRED_BACKUP
14058        if (!expectedStartTag.equals(parser.getName())) {
14059            if (DEBUG_BACKUP) {
14060                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14061            }
14062            return;
14063        }
14064
14065        // skip interfering stuff, then we're aligned with the backing implementation
14066        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14067        functor.apply(parser, userId);
14068    }
14069
14070    private interface BlobXmlRestorer {
14071        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14072    }
14073
14074    /**
14075     * Non-Binder method, support for the backup/restore mechanism: write the
14076     * full set of preferred activities in its canonical XML format.  Returns the
14077     * XML output as a byte array, or null if there is none.
14078     */
14079    @Override
14080    public byte[] getPreferredActivityBackup(int userId) {
14081        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14082            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14083        }
14084
14085        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14086        try {
14087            final XmlSerializer serializer = new FastXmlSerializer();
14088            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14089            serializer.startDocument(null, true);
14090            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14091
14092            synchronized (mPackages) {
14093                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14094            }
14095
14096            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14097            serializer.endDocument();
14098            serializer.flush();
14099        } catch (Exception e) {
14100            if (DEBUG_BACKUP) {
14101                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14102            }
14103            return null;
14104        }
14105
14106        return dataStream.toByteArray();
14107    }
14108
14109    @Override
14110    public void restorePreferredActivities(byte[] backup, int userId) {
14111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14112            throw new SecurityException("Only the system may call restorePreferredActivities()");
14113        }
14114
14115        try {
14116            final XmlPullParser parser = Xml.newPullParser();
14117            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14118            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14119                    new BlobXmlRestorer() {
14120                        @Override
14121                        public void apply(XmlPullParser parser, int userId)
14122                                throws XmlPullParserException, IOException {
14123                            synchronized (mPackages) {
14124                                mSettings.readPreferredActivitiesLPw(parser, userId);
14125                            }
14126                        }
14127                    } );
14128        } catch (Exception e) {
14129            if (DEBUG_BACKUP) {
14130                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14131            }
14132        }
14133    }
14134
14135    /**
14136     * Non-Binder method, support for the backup/restore mechanism: write the
14137     * default browser (etc) settings in its canonical XML format.  Returns the default
14138     * browser XML representation as a byte array, or null if there is none.
14139     */
14140    @Override
14141    public byte[] getDefaultAppsBackup(int userId) {
14142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14143            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14144        }
14145
14146        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14147        try {
14148            final XmlSerializer serializer = new FastXmlSerializer();
14149            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14150            serializer.startDocument(null, true);
14151            serializer.startTag(null, TAG_DEFAULT_APPS);
14152
14153            synchronized (mPackages) {
14154                mSettings.writeDefaultAppsLPr(serializer, userId);
14155            }
14156
14157            serializer.endTag(null, TAG_DEFAULT_APPS);
14158            serializer.endDocument();
14159            serializer.flush();
14160        } catch (Exception e) {
14161            if (DEBUG_BACKUP) {
14162                Slog.e(TAG, "Unable to write default apps for backup", e);
14163            }
14164            return null;
14165        }
14166
14167        return dataStream.toByteArray();
14168    }
14169
14170    @Override
14171    public void restoreDefaultApps(byte[] backup, int userId) {
14172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14173            throw new SecurityException("Only the system may call restoreDefaultApps()");
14174        }
14175
14176        try {
14177            final XmlPullParser parser = Xml.newPullParser();
14178            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14179            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14180                    new BlobXmlRestorer() {
14181                        @Override
14182                        public void apply(XmlPullParser parser, int userId)
14183                                throws XmlPullParserException, IOException {
14184                            synchronized (mPackages) {
14185                                mSettings.readDefaultAppsLPw(parser, userId);
14186                            }
14187                        }
14188                    } );
14189        } catch (Exception e) {
14190            if (DEBUG_BACKUP) {
14191                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14192            }
14193        }
14194    }
14195
14196    @Override
14197    public byte[] getIntentFilterVerificationBackup(int userId) {
14198        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14199            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14200        }
14201
14202        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14203        try {
14204            final XmlSerializer serializer = new FastXmlSerializer();
14205            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14206            serializer.startDocument(null, true);
14207            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14208
14209            synchronized (mPackages) {
14210                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14211            }
14212
14213            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14214            serializer.endDocument();
14215            serializer.flush();
14216        } catch (Exception e) {
14217            if (DEBUG_BACKUP) {
14218                Slog.e(TAG, "Unable to write default apps for backup", e);
14219            }
14220            return null;
14221        }
14222
14223        return dataStream.toByteArray();
14224    }
14225
14226    @Override
14227    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14228        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14229            throw new SecurityException("Only the system may call restorePreferredActivities()");
14230        }
14231
14232        try {
14233            final XmlPullParser parser = Xml.newPullParser();
14234            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14235            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14236                    new BlobXmlRestorer() {
14237                        @Override
14238                        public void apply(XmlPullParser parser, int userId)
14239                                throws XmlPullParserException, IOException {
14240                            synchronized (mPackages) {
14241                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14242                                mSettings.writeLPr();
14243                            }
14244                        }
14245                    } );
14246        } catch (Exception e) {
14247            if (DEBUG_BACKUP) {
14248                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14249            }
14250        }
14251    }
14252
14253    @Override
14254    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14255            int sourceUserId, int targetUserId, int flags) {
14256        mContext.enforceCallingOrSelfPermission(
14257                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14258        int callingUid = Binder.getCallingUid();
14259        enforceOwnerRights(ownerPackage, callingUid);
14260        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14261        if (intentFilter.countActions() == 0) {
14262            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14263            return;
14264        }
14265        synchronized (mPackages) {
14266            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14267                    ownerPackage, targetUserId, flags);
14268            CrossProfileIntentResolver resolver =
14269                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14270            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14271            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14272            if (existing != null) {
14273                int size = existing.size();
14274                for (int i = 0; i < size; i++) {
14275                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14276                        return;
14277                    }
14278                }
14279            }
14280            resolver.addFilter(newFilter);
14281            scheduleWritePackageRestrictionsLocked(sourceUserId);
14282        }
14283    }
14284
14285    @Override
14286    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14287        mContext.enforceCallingOrSelfPermission(
14288                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14289        int callingUid = Binder.getCallingUid();
14290        enforceOwnerRights(ownerPackage, callingUid);
14291        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14292        synchronized (mPackages) {
14293            CrossProfileIntentResolver resolver =
14294                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14295            ArraySet<CrossProfileIntentFilter> set =
14296                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14297            for (CrossProfileIntentFilter filter : set) {
14298                if (filter.getOwnerPackage().equals(ownerPackage)) {
14299                    resolver.removeFilter(filter);
14300                }
14301            }
14302            scheduleWritePackageRestrictionsLocked(sourceUserId);
14303        }
14304    }
14305
14306    // Enforcing that callingUid is owning pkg on userId
14307    private void enforceOwnerRights(String pkg, int callingUid) {
14308        // The system owns everything.
14309        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14310            return;
14311        }
14312        int callingUserId = UserHandle.getUserId(callingUid);
14313        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14314        if (pi == null) {
14315            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14316                    + callingUserId);
14317        }
14318        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14319            throw new SecurityException("Calling uid " + callingUid
14320                    + " does not own package " + pkg);
14321        }
14322    }
14323
14324    @Override
14325    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14326        Intent intent = new Intent(Intent.ACTION_MAIN);
14327        intent.addCategory(Intent.CATEGORY_HOME);
14328
14329        final int callingUserId = UserHandle.getCallingUserId();
14330        List<ResolveInfo> list = queryIntentActivities(intent, null,
14331                PackageManager.GET_META_DATA, callingUserId);
14332        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14333                true, false, false, callingUserId);
14334
14335        allHomeCandidates.clear();
14336        if (list != null) {
14337            for (ResolveInfo ri : list) {
14338                allHomeCandidates.add(ri);
14339            }
14340        }
14341        return (preferred == null || preferred.activityInfo == null)
14342                ? null
14343                : new ComponentName(preferred.activityInfo.packageName,
14344                        preferred.activityInfo.name);
14345    }
14346
14347    @Override
14348    public void setApplicationEnabledSetting(String appPackageName,
14349            int newState, int flags, int userId, String callingPackage) {
14350        if (!sUserManager.exists(userId)) return;
14351        if (callingPackage == null) {
14352            callingPackage = Integer.toString(Binder.getCallingUid());
14353        }
14354        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14355    }
14356
14357    @Override
14358    public void setComponentEnabledSetting(ComponentName componentName,
14359            int newState, int flags, int userId) {
14360        if (!sUserManager.exists(userId)) return;
14361        setEnabledSetting(componentName.getPackageName(),
14362                componentName.getClassName(), newState, flags, userId, null);
14363    }
14364
14365    private void setEnabledSetting(final String packageName, String className, int newState,
14366            final int flags, int userId, String callingPackage) {
14367        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14368              || newState == COMPONENT_ENABLED_STATE_ENABLED
14369              || newState == COMPONENT_ENABLED_STATE_DISABLED
14370              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14371              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14372            throw new IllegalArgumentException("Invalid new component state: "
14373                    + newState);
14374        }
14375        PackageSetting pkgSetting;
14376        final int uid = Binder.getCallingUid();
14377        final int permission = mContext.checkCallingOrSelfPermission(
14378                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14379        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14380        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14381        boolean sendNow = false;
14382        boolean isApp = (className == null);
14383        String componentName = isApp ? packageName : className;
14384        int packageUid = -1;
14385        ArrayList<String> components;
14386
14387        // writer
14388        synchronized (mPackages) {
14389            pkgSetting = mSettings.mPackages.get(packageName);
14390            if (pkgSetting == null) {
14391                if (className == null) {
14392                    throw new IllegalArgumentException(
14393                            "Unknown package: " + packageName);
14394                }
14395                throw new IllegalArgumentException(
14396                        "Unknown component: " + packageName
14397                        + "/" + className);
14398            }
14399            // Allow root and verify that userId is not being specified by a different user
14400            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14401                throw new SecurityException(
14402                        "Permission Denial: attempt to change component state from pid="
14403                        + Binder.getCallingPid()
14404                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14405            }
14406            if (className == null) {
14407                // We're dealing with an application/package level state change
14408                if (pkgSetting.getEnabled(userId) == newState) {
14409                    // Nothing to do
14410                    return;
14411                }
14412                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14413                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14414                    // Don't care about who enables an app.
14415                    callingPackage = null;
14416                }
14417                pkgSetting.setEnabled(newState, userId, callingPackage);
14418                // pkgSetting.pkg.mSetEnabled = newState;
14419            } else {
14420                // We're dealing with a component level state change
14421                // First, verify that this is a valid class name.
14422                PackageParser.Package pkg = pkgSetting.pkg;
14423                if (pkg == null || !pkg.hasComponentClassName(className)) {
14424                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14425                        throw new IllegalArgumentException("Component class " + className
14426                                + " does not exist in " + packageName);
14427                    } else {
14428                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14429                                + className + " does not exist in " + packageName);
14430                    }
14431                }
14432                switch (newState) {
14433                case COMPONENT_ENABLED_STATE_ENABLED:
14434                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14435                        return;
14436                    }
14437                    break;
14438                case COMPONENT_ENABLED_STATE_DISABLED:
14439                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14440                        return;
14441                    }
14442                    break;
14443                case COMPONENT_ENABLED_STATE_DEFAULT:
14444                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14445                        return;
14446                    }
14447                    break;
14448                default:
14449                    Slog.e(TAG, "Invalid new component state: " + newState);
14450                    return;
14451                }
14452            }
14453            scheduleWritePackageRestrictionsLocked(userId);
14454            components = mPendingBroadcasts.get(userId, packageName);
14455            final boolean newPackage = components == null;
14456            if (newPackage) {
14457                components = new ArrayList<String>();
14458            }
14459            if (!components.contains(componentName)) {
14460                components.add(componentName);
14461            }
14462            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14463                sendNow = true;
14464                // Purge entry from pending broadcast list if another one exists already
14465                // since we are sending one right away.
14466                mPendingBroadcasts.remove(userId, packageName);
14467            } else {
14468                if (newPackage) {
14469                    mPendingBroadcasts.put(userId, packageName, components);
14470                }
14471                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14472                    // Schedule a message
14473                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14474                }
14475            }
14476        }
14477
14478        long callingId = Binder.clearCallingIdentity();
14479        try {
14480            if (sendNow) {
14481                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14482                sendPackageChangedBroadcast(packageName,
14483                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14484            }
14485        } finally {
14486            Binder.restoreCallingIdentity(callingId);
14487        }
14488    }
14489
14490    private void sendPackageChangedBroadcast(String packageName,
14491            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14492        if (DEBUG_INSTALL)
14493            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14494                    + componentNames);
14495        Bundle extras = new Bundle(4);
14496        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14497        String nameList[] = new String[componentNames.size()];
14498        componentNames.toArray(nameList);
14499        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14500        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14501        extras.putInt(Intent.EXTRA_UID, packageUid);
14502        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14503                new int[] {UserHandle.getUserId(packageUid)});
14504    }
14505
14506    @Override
14507    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14508        if (!sUserManager.exists(userId)) return;
14509        final int uid = Binder.getCallingUid();
14510        final int permission = mContext.checkCallingOrSelfPermission(
14511                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14512        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14513        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14514        // writer
14515        synchronized (mPackages) {
14516            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14517                    allowedByPermission, uid, userId)) {
14518                scheduleWritePackageRestrictionsLocked(userId);
14519            }
14520        }
14521    }
14522
14523    @Override
14524    public String getInstallerPackageName(String packageName) {
14525        // reader
14526        synchronized (mPackages) {
14527            return mSettings.getInstallerPackageNameLPr(packageName);
14528        }
14529    }
14530
14531    @Override
14532    public int getApplicationEnabledSetting(String packageName, int userId) {
14533        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14534        int uid = Binder.getCallingUid();
14535        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14536        // reader
14537        synchronized (mPackages) {
14538            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14539        }
14540    }
14541
14542    @Override
14543    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14544        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14545        int uid = Binder.getCallingUid();
14546        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14547        // reader
14548        synchronized (mPackages) {
14549            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14550        }
14551    }
14552
14553    @Override
14554    public void enterSafeMode() {
14555        enforceSystemOrRoot("Only the system can request entering safe mode");
14556
14557        if (!mSystemReady) {
14558            mSafeMode = true;
14559        }
14560    }
14561
14562    @Override
14563    public void systemReady() {
14564        mSystemReady = true;
14565
14566        // Read the compatibilty setting when the system is ready.
14567        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14568                mContext.getContentResolver(),
14569                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14570        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14571        if (DEBUG_SETTINGS) {
14572            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14573        }
14574
14575        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14576
14577        synchronized (mPackages) {
14578            // Verify that all of the preferred activity components actually
14579            // exist.  It is possible for applications to be updated and at
14580            // that point remove a previously declared activity component that
14581            // had been set as a preferred activity.  We try to clean this up
14582            // the next time we encounter that preferred activity, but it is
14583            // possible for the user flow to never be able to return to that
14584            // situation so here we do a sanity check to make sure we haven't
14585            // left any junk around.
14586            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14587            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14588                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14589                removed.clear();
14590                for (PreferredActivity pa : pir.filterSet()) {
14591                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14592                        removed.add(pa);
14593                    }
14594                }
14595                if (removed.size() > 0) {
14596                    for (int r=0; r<removed.size(); r++) {
14597                        PreferredActivity pa = removed.get(r);
14598                        Slog.w(TAG, "Removing dangling preferred activity: "
14599                                + pa.mPref.mComponent);
14600                        pir.removeFilter(pa);
14601                    }
14602                    mSettings.writePackageRestrictionsLPr(
14603                            mSettings.mPreferredActivities.keyAt(i));
14604                }
14605            }
14606
14607            for (int userId : UserManagerService.getInstance().getUserIds()) {
14608                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14609                    grantPermissionsUserIds = ArrayUtils.appendInt(
14610                            grantPermissionsUserIds, userId);
14611                }
14612            }
14613        }
14614        sUserManager.systemReady();
14615
14616        // If we upgraded grant all default permissions before kicking off.
14617        for (int userId : grantPermissionsUserIds) {
14618            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14619        }
14620
14621        // Kick off any messages waiting for system ready
14622        if (mPostSystemReadyMessages != null) {
14623            for (Message msg : mPostSystemReadyMessages) {
14624                msg.sendToTarget();
14625            }
14626            mPostSystemReadyMessages = null;
14627        }
14628
14629        // Watch for external volumes that come and go over time
14630        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14631        storage.registerListener(mStorageListener);
14632
14633        mInstallerService.systemReady();
14634        mPackageDexOptimizer.systemReady();
14635
14636        MountServiceInternal mountServiceInternal = LocalServices.getService(
14637                MountServiceInternal.class);
14638        mountServiceInternal.addExternalStoragePolicy(
14639                new MountServiceInternal.ExternalStorageMountPolicy() {
14640            @Override
14641            public int getMountMode(int uid, String packageName) {
14642                if (Process.isIsolated(uid)) {
14643                    return Zygote.MOUNT_EXTERNAL_NONE;
14644                }
14645                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14646                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14647                }
14648                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14649                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14650                }
14651                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14652                    return Zygote.MOUNT_EXTERNAL_READ;
14653                }
14654                return Zygote.MOUNT_EXTERNAL_WRITE;
14655            }
14656
14657            @Override
14658            public boolean hasExternalStorage(int uid, String packageName) {
14659                return true;
14660            }
14661        });
14662    }
14663
14664    @Override
14665    public boolean isSafeMode() {
14666        return mSafeMode;
14667    }
14668
14669    @Override
14670    public boolean hasSystemUidErrors() {
14671        return mHasSystemUidErrors;
14672    }
14673
14674    static String arrayToString(int[] array) {
14675        StringBuffer buf = new StringBuffer(128);
14676        buf.append('[');
14677        if (array != null) {
14678            for (int i=0; i<array.length; i++) {
14679                if (i > 0) buf.append(", ");
14680                buf.append(array[i]);
14681            }
14682        }
14683        buf.append(']');
14684        return buf.toString();
14685    }
14686
14687    static class DumpState {
14688        public static final int DUMP_LIBS = 1 << 0;
14689        public static final int DUMP_FEATURES = 1 << 1;
14690        public static final int DUMP_RESOLVERS = 1 << 2;
14691        public static final int DUMP_PERMISSIONS = 1 << 3;
14692        public static final int DUMP_PACKAGES = 1 << 4;
14693        public static final int DUMP_SHARED_USERS = 1 << 5;
14694        public static final int DUMP_MESSAGES = 1 << 6;
14695        public static final int DUMP_PROVIDERS = 1 << 7;
14696        public static final int DUMP_VERIFIERS = 1 << 8;
14697        public static final int DUMP_PREFERRED = 1 << 9;
14698        public static final int DUMP_PREFERRED_XML = 1 << 10;
14699        public static final int DUMP_KEYSETS = 1 << 11;
14700        public static final int DUMP_VERSION = 1 << 12;
14701        public static final int DUMP_INSTALLS = 1 << 13;
14702        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14703        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14704
14705        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14706
14707        private int mTypes;
14708
14709        private int mOptions;
14710
14711        private boolean mTitlePrinted;
14712
14713        private SharedUserSetting mSharedUser;
14714
14715        public boolean isDumping(int type) {
14716            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14717                return true;
14718            }
14719
14720            return (mTypes & type) != 0;
14721        }
14722
14723        public void setDump(int type) {
14724            mTypes |= type;
14725        }
14726
14727        public boolean isOptionEnabled(int option) {
14728            return (mOptions & option) != 0;
14729        }
14730
14731        public void setOptionEnabled(int option) {
14732            mOptions |= option;
14733        }
14734
14735        public boolean onTitlePrinted() {
14736            final boolean printed = mTitlePrinted;
14737            mTitlePrinted = true;
14738            return printed;
14739        }
14740
14741        public boolean getTitlePrinted() {
14742            return mTitlePrinted;
14743        }
14744
14745        public void setTitlePrinted(boolean enabled) {
14746            mTitlePrinted = enabled;
14747        }
14748
14749        public SharedUserSetting getSharedUser() {
14750            return mSharedUser;
14751        }
14752
14753        public void setSharedUser(SharedUserSetting user) {
14754            mSharedUser = user;
14755        }
14756    }
14757
14758    @Override
14759    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14760        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14761                != PackageManager.PERMISSION_GRANTED) {
14762            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14763                    + Binder.getCallingPid()
14764                    + ", uid=" + Binder.getCallingUid()
14765                    + " without permission "
14766                    + android.Manifest.permission.DUMP);
14767            return;
14768        }
14769
14770        DumpState dumpState = new DumpState();
14771        boolean fullPreferred = false;
14772        boolean checkin = false;
14773
14774        String packageName = null;
14775        ArraySet<String> permissionNames = null;
14776
14777        int opti = 0;
14778        while (opti < args.length) {
14779            String opt = args[opti];
14780            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14781                break;
14782            }
14783            opti++;
14784
14785            if ("-a".equals(opt)) {
14786                // Right now we only know how to print all.
14787            } else if ("-h".equals(opt)) {
14788                pw.println("Package manager dump options:");
14789                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14790                pw.println("    --checkin: dump for a checkin");
14791                pw.println("    -f: print details of intent filters");
14792                pw.println("    -h: print this help");
14793                pw.println("  cmd may be one of:");
14794                pw.println("    l[ibraries]: list known shared libraries");
14795                pw.println("    f[ibraries]: list device features");
14796                pw.println("    k[eysets]: print known keysets");
14797                pw.println("    r[esolvers]: dump intent resolvers");
14798                pw.println("    perm[issions]: dump permissions");
14799                pw.println("    permission [name ...]: dump declaration and use of given permission");
14800                pw.println("    pref[erred]: print preferred package settings");
14801                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14802                pw.println("    prov[iders]: dump content providers");
14803                pw.println("    p[ackages]: dump installed packages");
14804                pw.println("    s[hared-users]: dump shared user IDs");
14805                pw.println("    m[essages]: print collected runtime messages");
14806                pw.println("    v[erifiers]: print package verifier info");
14807                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14808                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14809                pw.println("    version: print database version info");
14810                pw.println("    write: write current settings now");
14811                pw.println("    installs: details about install sessions");
14812                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14813                pw.println("    <package.name>: info about given package");
14814                return;
14815            } else if ("--checkin".equals(opt)) {
14816                checkin = true;
14817            } else if ("-f".equals(opt)) {
14818                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14819            } else {
14820                pw.println("Unknown argument: " + opt + "; use -h for help");
14821            }
14822        }
14823
14824        // Is the caller requesting to dump a particular piece of data?
14825        if (opti < args.length) {
14826            String cmd = args[opti];
14827            opti++;
14828            // Is this a package name?
14829            if ("android".equals(cmd) || cmd.contains(".")) {
14830                packageName = cmd;
14831                // When dumping a single package, we always dump all of its
14832                // filter information since the amount of data will be reasonable.
14833                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14834            } else if ("check-permission".equals(cmd)) {
14835                if (opti >= args.length) {
14836                    pw.println("Error: check-permission missing permission argument");
14837                    return;
14838                }
14839                String perm = args[opti];
14840                opti++;
14841                if (opti >= args.length) {
14842                    pw.println("Error: check-permission missing package argument");
14843                    return;
14844                }
14845                String pkg = args[opti];
14846                opti++;
14847                int user = UserHandle.getUserId(Binder.getCallingUid());
14848                if (opti < args.length) {
14849                    try {
14850                        user = Integer.parseInt(args[opti]);
14851                    } catch (NumberFormatException e) {
14852                        pw.println("Error: check-permission user argument is not a number: "
14853                                + args[opti]);
14854                        return;
14855                    }
14856                }
14857                pw.println(checkPermission(perm, pkg, user));
14858                return;
14859            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14860                dumpState.setDump(DumpState.DUMP_LIBS);
14861            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14862                dumpState.setDump(DumpState.DUMP_FEATURES);
14863            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14864                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14865            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14866                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14867            } else if ("permission".equals(cmd)) {
14868                if (opti >= args.length) {
14869                    pw.println("Error: permission requires permission name");
14870                    return;
14871                }
14872                permissionNames = new ArraySet<>();
14873                while (opti < args.length) {
14874                    permissionNames.add(args[opti]);
14875                    opti++;
14876                }
14877                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14878                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14879            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14880                dumpState.setDump(DumpState.DUMP_PREFERRED);
14881            } else if ("preferred-xml".equals(cmd)) {
14882                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14883                if (opti < args.length && "--full".equals(args[opti])) {
14884                    fullPreferred = true;
14885                    opti++;
14886                }
14887            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14888                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14889            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14890                dumpState.setDump(DumpState.DUMP_PACKAGES);
14891            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14892                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14893            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14894                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14895            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14896                dumpState.setDump(DumpState.DUMP_MESSAGES);
14897            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14898                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14899            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14900                    || "intent-filter-verifiers".equals(cmd)) {
14901                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14902            } else if ("version".equals(cmd)) {
14903                dumpState.setDump(DumpState.DUMP_VERSION);
14904            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14905                dumpState.setDump(DumpState.DUMP_KEYSETS);
14906            } else if ("installs".equals(cmd)) {
14907                dumpState.setDump(DumpState.DUMP_INSTALLS);
14908            } else if ("write".equals(cmd)) {
14909                synchronized (mPackages) {
14910                    mSettings.writeLPr();
14911                    pw.println("Settings written.");
14912                    return;
14913                }
14914            }
14915        }
14916
14917        if (checkin) {
14918            pw.println("vers,1");
14919        }
14920
14921        // reader
14922        synchronized (mPackages) {
14923            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14924                if (!checkin) {
14925                    if (dumpState.onTitlePrinted())
14926                        pw.println();
14927                    pw.println("Database versions:");
14928                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14929                }
14930            }
14931
14932            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14933                if (!checkin) {
14934                    if (dumpState.onTitlePrinted())
14935                        pw.println();
14936                    pw.println("Verifiers:");
14937                    pw.print("  Required: ");
14938                    pw.print(mRequiredVerifierPackage);
14939                    pw.print(" (uid=");
14940                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14941                    pw.println(")");
14942                } else if (mRequiredVerifierPackage != null) {
14943                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14944                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14945                }
14946            }
14947
14948            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14949                    packageName == null) {
14950                if (mIntentFilterVerifierComponent != null) {
14951                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14952                    if (!checkin) {
14953                        if (dumpState.onTitlePrinted())
14954                            pw.println();
14955                        pw.println("Intent Filter Verifier:");
14956                        pw.print("  Using: ");
14957                        pw.print(verifierPackageName);
14958                        pw.print(" (uid=");
14959                        pw.print(getPackageUid(verifierPackageName, 0));
14960                        pw.println(")");
14961                    } else if (verifierPackageName != null) {
14962                        pw.print("ifv,"); pw.print(verifierPackageName);
14963                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14964                    }
14965                } else {
14966                    pw.println();
14967                    pw.println("No Intent Filter Verifier available!");
14968                }
14969            }
14970
14971            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14972                boolean printedHeader = false;
14973                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14974                while (it.hasNext()) {
14975                    String name = it.next();
14976                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14977                    if (!checkin) {
14978                        if (!printedHeader) {
14979                            if (dumpState.onTitlePrinted())
14980                                pw.println();
14981                            pw.println("Libraries:");
14982                            printedHeader = true;
14983                        }
14984                        pw.print("  ");
14985                    } else {
14986                        pw.print("lib,");
14987                    }
14988                    pw.print(name);
14989                    if (!checkin) {
14990                        pw.print(" -> ");
14991                    }
14992                    if (ent.path != null) {
14993                        if (!checkin) {
14994                            pw.print("(jar) ");
14995                            pw.print(ent.path);
14996                        } else {
14997                            pw.print(",jar,");
14998                            pw.print(ent.path);
14999                        }
15000                    } else {
15001                        if (!checkin) {
15002                            pw.print("(apk) ");
15003                            pw.print(ent.apk);
15004                        } else {
15005                            pw.print(",apk,");
15006                            pw.print(ent.apk);
15007                        }
15008                    }
15009                    pw.println();
15010                }
15011            }
15012
15013            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15014                if (dumpState.onTitlePrinted())
15015                    pw.println();
15016                if (!checkin) {
15017                    pw.println("Features:");
15018                }
15019                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15020                while (it.hasNext()) {
15021                    String name = it.next();
15022                    if (!checkin) {
15023                        pw.print("  ");
15024                    } else {
15025                        pw.print("feat,");
15026                    }
15027                    pw.println(name);
15028                }
15029            }
15030
15031            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15032                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15033                        : "Activity Resolver Table:", "  ", packageName,
15034                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15035                    dumpState.setTitlePrinted(true);
15036                }
15037                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15038                        : "Receiver Resolver Table:", "  ", packageName,
15039                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15040                    dumpState.setTitlePrinted(true);
15041                }
15042                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15043                        : "Service Resolver Table:", "  ", packageName,
15044                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15045                    dumpState.setTitlePrinted(true);
15046                }
15047                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15048                        : "Provider Resolver Table:", "  ", packageName,
15049                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15050                    dumpState.setTitlePrinted(true);
15051                }
15052            }
15053
15054            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15055                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15056                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15057                    int user = mSettings.mPreferredActivities.keyAt(i);
15058                    if (pir.dump(pw,
15059                            dumpState.getTitlePrinted()
15060                                ? "\nPreferred Activities User " + user + ":"
15061                                : "Preferred Activities User " + user + ":", "  ",
15062                            packageName, true, false)) {
15063                        dumpState.setTitlePrinted(true);
15064                    }
15065                }
15066            }
15067
15068            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15069                pw.flush();
15070                FileOutputStream fout = new FileOutputStream(fd);
15071                BufferedOutputStream str = new BufferedOutputStream(fout);
15072                XmlSerializer serializer = new FastXmlSerializer();
15073                try {
15074                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15075                    serializer.startDocument(null, true);
15076                    serializer.setFeature(
15077                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15078                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15079                    serializer.endDocument();
15080                    serializer.flush();
15081                } catch (IllegalArgumentException e) {
15082                    pw.println("Failed writing: " + e);
15083                } catch (IllegalStateException e) {
15084                    pw.println("Failed writing: " + e);
15085                } catch (IOException e) {
15086                    pw.println("Failed writing: " + e);
15087                }
15088            }
15089
15090            if (!checkin
15091                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15092                    && packageName == null) {
15093                pw.println();
15094                int count = mSettings.mPackages.size();
15095                if (count == 0) {
15096                    pw.println("No applications!");
15097                    pw.println();
15098                } else {
15099                    final String prefix = "  ";
15100                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15101                    if (allPackageSettings.size() == 0) {
15102                        pw.println("No domain preferred apps!");
15103                        pw.println();
15104                    } else {
15105                        pw.println("App verification status:");
15106                        pw.println();
15107                        count = 0;
15108                        for (PackageSetting ps : allPackageSettings) {
15109                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15110                            if (ivi == null || ivi.getPackageName() == null) continue;
15111                            pw.println(prefix + "Package: " + ivi.getPackageName());
15112                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15113                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15114                            pw.println();
15115                            count++;
15116                        }
15117                        if (count == 0) {
15118                            pw.println(prefix + "No app verification established.");
15119                            pw.println();
15120                        }
15121                        for (int userId : sUserManager.getUserIds()) {
15122                            pw.println("App linkages for user " + userId + ":");
15123                            pw.println();
15124                            count = 0;
15125                            for (PackageSetting ps : allPackageSettings) {
15126                                final long status = ps.getDomainVerificationStatusForUser(userId);
15127                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15128                                    continue;
15129                                }
15130                                pw.println(prefix + "Package: " + ps.name);
15131                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15132                                String statusStr = IntentFilterVerificationInfo.
15133                                        getStatusStringFromValue(status);
15134                                pw.println(prefix + "Status:  " + statusStr);
15135                                pw.println();
15136                                count++;
15137                            }
15138                            if (count == 0) {
15139                                pw.println(prefix + "No configured app linkages.");
15140                                pw.println();
15141                            }
15142                        }
15143                    }
15144                }
15145            }
15146
15147            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15148                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15149                if (packageName == null && permissionNames == null) {
15150                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15151                        if (iperm == 0) {
15152                            if (dumpState.onTitlePrinted())
15153                                pw.println();
15154                            pw.println("AppOp Permissions:");
15155                        }
15156                        pw.print("  AppOp Permission ");
15157                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15158                        pw.println(":");
15159                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15160                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15161                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15162                        }
15163                    }
15164                }
15165            }
15166
15167            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15168                boolean printedSomething = false;
15169                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15170                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15171                        continue;
15172                    }
15173                    if (!printedSomething) {
15174                        if (dumpState.onTitlePrinted())
15175                            pw.println();
15176                        pw.println("Registered ContentProviders:");
15177                        printedSomething = true;
15178                    }
15179                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15180                    pw.print("    "); pw.println(p.toString());
15181                }
15182                printedSomething = false;
15183                for (Map.Entry<String, PackageParser.Provider> entry :
15184                        mProvidersByAuthority.entrySet()) {
15185                    PackageParser.Provider p = entry.getValue();
15186                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15187                        continue;
15188                    }
15189                    if (!printedSomething) {
15190                        if (dumpState.onTitlePrinted())
15191                            pw.println();
15192                        pw.println("ContentProvider Authorities:");
15193                        printedSomething = true;
15194                    }
15195                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15196                    pw.print("    "); pw.println(p.toString());
15197                    if (p.info != null && p.info.applicationInfo != null) {
15198                        final String appInfo = p.info.applicationInfo.toString();
15199                        pw.print("      applicationInfo="); pw.println(appInfo);
15200                    }
15201                }
15202            }
15203
15204            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15205                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15206            }
15207
15208            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15209                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15210            }
15211
15212            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15213                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15214            }
15215
15216            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15217                // XXX should handle packageName != null by dumping only install data that
15218                // the given package is involved with.
15219                if (dumpState.onTitlePrinted()) pw.println();
15220                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15221            }
15222
15223            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15224                if (dumpState.onTitlePrinted()) pw.println();
15225                mSettings.dumpReadMessagesLPr(pw, dumpState);
15226
15227                pw.println();
15228                pw.println("Package warning messages:");
15229                BufferedReader in = null;
15230                String line = null;
15231                try {
15232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15233                    while ((line = in.readLine()) != null) {
15234                        if (line.contains("ignored: updated version")) continue;
15235                        pw.println(line);
15236                    }
15237                } catch (IOException ignored) {
15238                } finally {
15239                    IoUtils.closeQuietly(in);
15240                }
15241            }
15242
15243            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15244                BufferedReader in = null;
15245                String line = null;
15246                try {
15247                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15248                    while ((line = in.readLine()) != null) {
15249                        if (line.contains("ignored: updated version")) continue;
15250                        pw.print("msg,");
15251                        pw.println(line);
15252                    }
15253                } catch (IOException ignored) {
15254                } finally {
15255                    IoUtils.closeQuietly(in);
15256                }
15257            }
15258        }
15259    }
15260
15261    private String dumpDomainString(String packageName) {
15262        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15263        List<IntentFilter> filters = getAllIntentFilters(packageName);
15264
15265        ArraySet<String> result = new ArraySet<>();
15266        if (iviList.size() > 0) {
15267            for (IntentFilterVerificationInfo ivi : iviList) {
15268                for (String host : ivi.getDomains()) {
15269                    result.add(host);
15270                }
15271            }
15272        }
15273        if (filters != null && filters.size() > 0) {
15274            for (IntentFilter filter : filters) {
15275                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15276                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15277                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15278                    result.addAll(filter.getHostsList());
15279                }
15280            }
15281        }
15282
15283        StringBuilder sb = new StringBuilder(result.size() * 16);
15284        for (String domain : result) {
15285            if (sb.length() > 0) sb.append(" ");
15286            sb.append(domain);
15287        }
15288        return sb.toString();
15289    }
15290
15291    // ------- apps on sdcard specific code -------
15292    static final boolean DEBUG_SD_INSTALL = false;
15293
15294    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15295
15296    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15297
15298    private boolean mMediaMounted = false;
15299
15300    static String getEncryptKey() {
15301        try {
15302            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15303                    SD_ENCRYPTION_KEYSTORE_NAME);
15304            if (sdEncKey == null) {
15305                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15306                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15307                if (sdEncKey == null) {
15308                    Slog.e(TAG, "Failed to create encryption keys");
15309                    return null;
15310                }
15311            }
15312            return sdEncKey;
15313        } catch (NoSuchAlgorithmException nsae) {
15314            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15315            return null;
15316        } catch (IOException ioe) {
15317            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15318            return null;
15319        }
15320    }
15321
15322    /*
15323     * Update media status on PackageManager.
15324     */
15325    @Override
15326    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15327        int callingUid = Binder.getCallingUid();
15328        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15329            throw new SecurityException("Media status can only be updated by the system");
15330        }
15331        // reader; this apparently protects mMediaMounted, but should probably
15332        // be a different lock in that case.
15333        synchronized (mPackages) {
15334            Log.i(TAG, "Updating external media status from "
15335                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15336                    + (mediaStatus ? "mounted" : "unmounted"));
15337            if (DEBUG_SD_INSTALL)
15338                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15339                        + ", mMediaMounted=" + mMediaMounted);
15340            if (mediaStatus == mMediaMounted) {
15341                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15342                        : 0, -1);
15343                mHandler.sendMessage(msg);
15344                return;
15345            }
15346            mMediaMounted = mediaStatus;
15347        }
15348        // Queue up an async operation since the package installation may take a
15349        // little while.
15350        mHandler.post(new Runnable() {
15351            public void run() {
15352                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15353            }
15354        });
15355    }
15356
15357    /**
15358     * Called by MountService when the initial ASECs to scan are available.
15359     * Should block until all the ASEC containers are finished being scanned.
15360     */
15361    public void scanAvailableAsecs() {
15362        updateExternalMediaStatusInner(true, false, false);
15363        if (mShouldRestoreconData) {
15364            SELinuxMMAC.setRestoreconDone();
15365            mShouldRestoreconData = false;
15366        }
15367    }
15368
15369    /*
15370     * Collect information of applications on external media, map them against
15371     * existing containers and update information based on current mount status.
15372     * Please note that we always have to report status if reportStatus has been
15373     * set to true especially when unloading packages.
15374     */
15375    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15376            boolean externalStorage) {
15377        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15378        int[] uidArr = EmptyArray.INT;
15379
15380        final String[] list = PackageHelper.getSecureContainerList();
15381        if (ArrayUtils.isEmpty(list)) {
15382            Log.i(TAG, "No secure containers found");
15383        } else {
15384            // Process list of secure containers and categorize them
15385            // as active or stale based on their package internal state.
15386
15387            // reader
15388            synchronized (mPackages) {
15389                for (String cid : list) {
15390                    // Leave stages untouched for now; installer service owns them
15391                    if (PackageInstallerService.isStageName(cid)) continue;
15392
15393                    if (DEBUG_SD_INSTALL)
15394                        Log.i(TAG, "Processing container " + cid);
15395                    String pkgName = getAsecPackageName(cid);
15396                    if (pkgName == null) {
15397                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15398                        continue;
15399                    }
15400                    if (DEBUG_SD_INSTALL)
15401                        Log.i(TAG, "Looking for pkg : " + pkgName);
15402
15403                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15404                    if (ps == null) {
15405                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15406                        continue;
15407                    }
15408
15409                    /*
15410                     * Skip packages that are not external if we're unmounting
15411                     * external storage.
15412                     */
15413                    if (externalStorage && !isMounted && !isExternal(ps)) {
15414                        continue;
15415                    }
15416
15417                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15418                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15419                    // The package status is changed only if the code path
15420                    // matches between settings and the container id.
15421                    if (ps.codePathString != null
15422                            && ps.codePathString.startsWith(args.getCodePath())) {
15423                        if (DEBUG_SD_INSTALL) {
15424                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15425                                    + " at code path: " + ps.codePathString);
15426                        }
15427
15428                        // We do have a valid package installed on sdcard
15429                        processCids.put(args, ps.codePathString);
15430                        final int uid = ps.appId;
15431                        if (uid != -1) {
15432                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15433                        }
15434                    } else {
15435                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15436                                + ps.codePathString);
15437                    }
15438                }
15439            }
15440
15441            Arrays.sort(uidArr);
15442        }
15443
15444        // Process packages with valid entries.
15445        if (isMounted) {
15446            if (DEBUG_SD_INSTALL)
15447                Log.i(TAG, "Loading packages");
15448            loadMediaPackages(processCids, uidArr);
15449            startCleaningPackages();
15450            mInstallerService.onSecureContainersAvailable();
15451        } else {
15452            if (DEBUG_SD_INSTALL)
15453                Log.i(TAG, "Unloading packages");
15454            unloadMediaPackages(processCids, uidArr, reportStatus);
15455        }
15456    }
15457
15458    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15459            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15460        final int size = infos.size();
15461        final String[] packageNames = new String[size];
15462        final int[] packageUids = new int[size];
15463        for (int i = 0; i < size; i++) {
15464            final ApplicationInfo info = infos.get(i);
15465            packageNames[i] = info.packageName;
15466            packageUids[i] = info.uid;
15467        }
15468        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15469                finishedReceiver);
15470    }
15471
15472    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15473            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15474        sendResourcesChangedBroadcast(mediaStatus, replacing,
15475                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15476    }
15477
15478    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15479            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15480        int size = pkgList.length;
15481        if (size > 0) {
15482            // Send broadcasts here
15483            Bundle extras = new Bundle();
15484            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15485            if (uidArr != null) {
15486                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15487            }
15488            if (replacing) {
15489                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15490            }
15491            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15492                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15493            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15494        }
15495    }
15496
15497   /*
15498     * Look at potentially valid container ids from processCids If package
15499     * information doesn't match the one on record or package scanning fails,
15500     * the cid is added to list of removeCids. We currently don't delete stale
15501     * containers.
15502     */
15503    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15504        ArrayList<String> pkgList = new ArrayList<String>();
15505        Set<AsecInstallArgs> keys = processCids.keySet();
15506
15507        for (AsecInstallArgs args : keys) {
15508            String codePath = processCids.get(args);
15509            if (DEBUG_SD_INSTALL)
15510                Log.i(TAG, "Loading container : " + args.cid);
15511            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15512            try {
15513                // Make sure there are no container errors first.
15514                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15515                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15516                            + " when installing from sdcard");
15517                    continue;
15518                }
15519                // Check code path here.
15520                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15521                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15522                            + " does not match one in settings " + codePath);
15523                    continue;
15524                }
15525                // Parse package
15526                int parseFlags = mDefParseFlags;
15527                if (args.isExternalAsec()) {
15528                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15529                }
15530                if (args.isFwdLocked()) {
15531                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15532                }
15533
15534                synchronized (mInstallLock) {
15535                    PackageParser.Package pkg = null;
15536                    try {
15537                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15538                    } catch (PackageManagerException e) {
15539                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15540                    }
15541                    // Scan the package
15542                    if (pkg != null) {
15543                        /*
15544                         * TODO why is the lock being held? doPostInstall is
15545                         * called in other places without the lock. This needs
15546                         * to be straightened out.
15547                         */
15548                        // writer
15549                        synchronized (mPackages) {
15550                            retCode = PackageManager.INSTALL_SUCCEEDED;
15551                            pkgList.add(pkg.packageName);
15552                            // Post process args
15553                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15554                                    pkg.applicationInfo.uid);
15555                        }
15556                    } else {
15557                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15558                    }
15559                }
15560
15561            } finally {
15562                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15563                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15564                }
15565            }
15566        }
15567        // writer
15568        synchronized (mPackages) {
15569            // If the platform SDK has changed since the last time we booted,
15570            // we need to re-grant app permission to catch any new ones that
15571            // appear. This is really a hack, and means that apps can in some
15572            // cases get permissions that the user didn't initially explicitly
15573            // allow... it would be nice to have some better way to handle
15574            // this situation.
15575            final VersionInfo ver = mSettings.getExternalVersion();
15576
15577            int updateFlags = UPDATE_PERMISSIONS_ALL;
15578            if (ver.sdkVersion != mSdkVersion) {
15579                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15580                        + mSdkVersion + "; regranting permissions for external");
15581                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15582            }
15583            updatePermissionsLPw(null, null, updateFlags);
15584
15585            // Yay, everything is now upgraded
15586            ver.forceCurrent();
15587
15588            // can downgrade to reader
15589            // Persist settings
15590            mSettings.writeLPr();
15591        }
15592        // Send a broadcast to let everyone know we are done processing
15593        if (pkgList.size() > 0) {
15594            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15595        }
15596    }
15597
15598   /*
15599     * Utility method to unload a list of specified containers
15600     */
15601    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15602        // Just unmount all valid containers.
15603        for (AsecInstallArgs arg : cidArgs) {
15604            synchronized (mInstallLock) {
15605                arg.doPostDeleteLI(false);
15606           }
15607       }
15608   }
15609
15610    /*
15611     * Unload packages mounted on external media. This involves deleting package
15612     * data from internal structures, sending broadcasts about diabled packages,
15613     * gc'ing to free up references, unmounting all secure containers
15614     * corresponding to packages on external media, and posting a
15615     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15616     * that we always have to post this message if status has been requested no
15617     * matter what.
15618     */
15619    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15620            final boolean reportStatus) {
15621        if (DEBUG_SD_INSTALL)
15622            Log.i(TAG, "unloading media packages");
15623        ArrayList<String> pkgList = new ArrayList<String>();
15624        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15625        final Set<AsecInstallArgs> keys = processCids.keySet();
15626        for (AsecInstallArgs args : keys) {
15627            String pkgName = args.getPackageName();
15628            if (DEBUG_SD_INSTALL)
15629                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15630            // Delete package internally
15631            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15632            synchronized (mInstallLock) {
15633                boolean res = deletePackageLI(pkgName, null, false, null, null,
15634                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15635                if (res) {
15636                    pkgList.add(pkgName);
15637                } else {
15638                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15639                    failedList.add(args);
15640                }
15641            }
15642        }
15643
15644        // reader
15645        synchronized (mPackages) {
15646            // We didn't update the settings after removing each package;
15647            // write them now for all packages.
15648            mSettings.writeLPr();
15649        }
15650
15651        // We have to absolutely send UPDATED_MEDIA_STATUS only
15652        // after confirming that all the receivers processed the ordered
15653        // broadcast when packages get disabled, force a gc to clean things up.
15654        // and unload all the containers.
15655        if (pkgList.size() > 0) {
15656            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15657                    new IIntentReceiver.Stub() {
15658                public void performReceive(Intent intent, int resultCode, String data,
15659                        Bundle extras, boolean ordered, boolean sticky,
15660                        int sendingUser) throws RemoteException {
15661                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15662                            reportStatus ? 1 : 0, 1, keys);
15663                    mHandler.sendMessage(msg);
15664                }
15665            });
15666        } else {
15667            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15668                    keys);
15669            mHandler.sendMessage(msg);
15670        }
15671    }
15672
15673    private void loadPrivatePackages(VolumeInfo vol) {
15674        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15675        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15676        synchronized (mInstallLock) {
15677        synchronized (mPackages) {
15678            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15679            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15680            for (PackageSetting ps : packages) {
15681                final PackageParser.Package pkg;
15682                try {
15683                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15684                    loaded.add(pkg.applicationInfo);
15685                } catch (PackageManagerException e) {
15686                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15687                }
15688
15689                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15690                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15691                }
15692            }
15693
15694            int updateFlags = UPDATE_PERMISSIONS_ALL;
15695            if (ver.sdkVersion != mSdkVersion) {
15696                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15697                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15698                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15699            }
15700            updatePermissionsLPw(null, null, updateFlags);
15701
15702            // Yay, everything is now upgraded
15703            ver.forceCurrent();
15704
15705            mSettings.writeLPr();
15706        }
15707        }
15708
15709        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15710        sendResourcesChangedBroadcast(true, false, loaded, null);
15711    }
15712
15713    private void unloadPrivatePackages(VolumeInfo vol) {
15714        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15715        synchronized (mInstallLock) {
15716        synchronized (mPackages) {
15717            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15718            for (PackageSetting ps : packages) {
15719                if (ps.pkg == null) continue;
15720
15721                final ApplicationInfo info = ps.pkg.applicationInfo;
15722                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15723                if (deletePackageLI(ps.name, null, false, null, null,
15724                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15725                    unloaded.add(info);
15726                } else {
15727                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15728                }
15729            }
15730
15731            mSettings.writeLPr();
15732        }
15733        }
15734
15735        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15736        sendResourcesChangedBroadcast(false, false, unloaded, null);
15737    }
15738
15739    /**
15740     * Examine all users present on given mounted volume, and destroy data
15741     * belonging to users that are no longer valid, or whose user ID has been
15742     * recycled.
15743     */
15744    private void reconcileUsers(String volumeUuid) {
15745        final File[] files = FileUtils
15746                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15747        for (File file : files) {
15748            if (!file.isDirectory()) continue;
15749
15750            final int userId;
15751            final UserInfo info;
15752            try {
15753                userId = Integer.parseInt(file.getName());
15754                info = sUserManager.getUserInfo(userId);
15755            } catch (NumberFormatException e) {
15756                Slog.w(TAG, "Invalid user directory " + file);
15757                continue;
15758            }
15759
15760            boolean destroyUser = false;
15761            if (info == null) {
15762                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15763                        + " because no matching user was found");
15764                destroyUser = true;
15765            } else {
15766                try {
15767                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15768                } catch (IOException e) {
15769                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15770                            + " because we failed to enforce serial number: " + e);
15771                    destroyUser = true;
15772                }
15773            }
15774
15775            if (destroyUser) {
15776                synchronized (mInstallLock) {
15777                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15778                }
15779            }
15780        }
15781
15782        final UserManager um = mContext.getSystemService(UserManager.class);
15783        for (UserInfo user : um.getUsers()) {
15784            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15785            if (userDir.exists()) continue;
15786
15787            try {
15788                UserManagerService.prepareUserDirectory(userDir);
15789                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15790            } catch (IOException e) {
15791                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15792            }
15793        }
15794    }
15795
15796    /**
15797     * Examine all apps present on given mounted volume, and destroy apps that
15798     * aren't expected, either due to uninstallation or reinstallation on
15799     * another volume.
15800     */
15801    private void reconcileApps(String volumeUuid) {
15802        final File[] files = FileUtils
15803                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15804        for (File file : files) {
15805            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15806                    && !PackageInstallerService.isStageName(file.getName());
15807            if (!isPackage) {
15808                // Ignore entries which are not packages
15809                continue;
15810            }
15811
15812            boolean destroyApp = false;
15813            String packageName = null;
15814            try {
15815                final PackageLite pkg = PackageParser.parsePackageLite(file,
15816                        PackageParser.PARSE_MUST_BE_APK);
15817                packageName = pkg.packageName;
15818
15819                synchronized (mPackages) {
15820                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15821                    if (ps == null) {
15822                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15823                                + volumeUuid + " because we found no install record");
15824                        destroyApp = true;
15825                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15826                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15827                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15828                        destroyApp = true;
15829                    }
15830                }
15831
15832            } catch (PackageParserException e) {
15833                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15834                destroyApp = true;
15835            }
15836
15837            if (destroyApp) {
15838                synchronized (mInstallLock) {
15839                    if (packageName != null) {
15840                        removeDataDirsLI(volumeUuid, packageName);
15841                    }
15842                    if (file.isDirectory()) {
15843                        mInstaller.rmPackageDir(file.getAbsolutePath());
15844                    } else {
15845                        file.delete();
15846                    }
15847                }
15848            }
15849        }
15850    }
15851
15852    private void unfreezePackage(String packageName) {
15853        synchronized (mPackages) {
15854            final PackageSetting ps = mSettings.mPackages.get(packageName);
15855            if (ps != null) {
15856                ps.frozen = false;
15857            }
15858        }
15859    }
15860
15861    @Override
15862    public int movePackage(final String packageName, final String volumeUuid) {
15863        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15864
15865        final int moveId = mNextMoveId.getAndIncrement();
15866        try {
15867            movePackageInternal(packageName, volumeUuid, moveId);
15868        } catch (PackageManagerException e) {
15869            Slog.w(TAG, "Failed to move " + packageName, e);
15870            mMoveCallbacks.notifyStatusChanged(moveId,
15871                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15872        }
15873        return moveId;
15874    }
15875
15876    private void movePackageInternal(final String packageName, final String volumeUuid,
15877            final int moveId) throws PackageManagerException {
15878        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15879        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15880        final PackageManager pm = mContext.getPackageManager();
15881
15882        final boolean currentAsec;
15883        final String currentVolumeUuid;
15884        final File codeFile;
15885        final String installerPackageName;
15886        final String packageAbiOverride;
15887        final int appId;
15888        final String seinfo;
15889        final String label;
15890
15891        // reader
15892        synchronized (mPackages) {
15893            final PackageParser.Package pkg = mPackages.get(packageName);
15894            final PackageSetting ps = mSettings.mPackages.get(packageName);
15895            if (pkg == null || ps == null) {
15896                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15897            }
15898
15899            if (pkg.applicationInfo.isSystemApp()) {
15900                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15901                        "Cannot move system application");
15902            }
15903
15904            if (pkg.applicationInfo.isExternalAsec()) {
15905                currentAsec = true;
15906                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15907            } else if (pkg.applicationInfo.isForwardLocked()) {
15908                currentAsec = true;
15909                currentVolumeUuid = "forward_locked";
15910            } else {
15911                currentAsec = false;
15912                currentVolumeUuid = ps.volumeUuid;
15913
15914                final File probe = new File(pkg.codePath);
15915                final File probeOat = new File(probe, "oat");
15916                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15917                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15918                            "Move only supported for modern cluster style installs");
15919                }
15920            }
15921
15922            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15923                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15924                        "Package already moved to " + volumeUuid);
15925            }
15926
15927            if (ps.frozen) {
15928                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15929                        "Failed to move already frozen package");
15930            }
15931            ps.frozen = true;
15932
15933            codeFile = new File(pkg.codePath);
15934            installerPackageName = ps.installerPackageName;
15935            packageAbiOverride = ps.cpuAbiOverrideString;
15936            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15937            seinfo = pkg.applicationInfo.seinfo;
15938            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15939        }
15940
15941        // Now that we're guarded by frozen state, kill app during move
15942        final long token = Binder.clearCallingIdentity();
15943        try {
15944            killApplication(packageName, appId, "move pkg");
15945        } finally {
15946            Binder.restoreCallingIdentity(token);
15947        }
15948
15949        final Bundle extras = new Bundle();
15950        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15951        extras.putString(Intent.EXTRA_TITLE, label);
15952        mMoveCallbacks.notifyCreated(moveId, extras);
15953
15954        int installFlags;
15955        final boolean moveCompleteApp;
15956        final File measurePath;
15957
15958        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15959            installFlags = INSTALL_INTERNAL;
15960            moveCompleteApp = !currentAsec;
15961            measurePath = Environment.getDataAppDirectory(volumeUuid);
15962        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15963            installFlags = INSTALL_EXTERNAL;
15964            moveCompleteApp = false;
15965            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15966        } else {
15967            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15968            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15969                    || !volume.isMountedWritable()) {
15970                unfreezePackage(packageName);
15971                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15972                        "Move location not mounted private volume");
15973            }
15974
15975            Preconditions.checkState(!currentAsec);
15976
15977            installFlags = INSTALL_INTERNAL;
15978            moveCompleteApp = true;
15979            measurePath = Environment.getDataAppDirectory(volumeUuid);
15980        }
15981
15982        final PackageStats stats = new PackageStats(null, -1);
15983        synchronized (mInstaller) {
15984            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15985                unfreezePackage(packageName);
15986                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15987                        "Failed to measure package size");
15988            }
15989        }
15990
15991        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15992                + stats.dataSize);
15993
15994        final long startFreeBytes = measurePath.getFreeSpace();
15995        final long sizeBytes;
15996        if (moveCompleteApp) {
15997            sizeBytes = stats.codeSize + stats.dataSize;
15998        } else {
15999            sizeBytes = stats.codeSize;
16000        }
16001
16002        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16003            unfreezePackage(packageName);
16004            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16005                    "Not enough free space to move");
16006        }
16007
16008        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16009
16010        final CountDownLatch installedLatch = new CountDownLatch(1);
16011        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16012            @Override
16013            public void onUserActionRequired(Intent intent) throws RemoteException {
16014                throw new IllegalStateException();
16015            }
16016
16017            @Override
16018            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16019                    Bundle extras) throws RemoteException {
16020                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16021                        + PackageManager.installStatusToString(returnCode, msg));
16022
16023                installedLatch.countDown();
16024
16025                // Regardless of success or failure of the move operation,
16026                // always unfreeze the package
16027                unfreezePackage(packageName);
16028
16029                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16030                switch (status) {
16031                    case PackageInstaller.STATUS_SUCCESS:
16032                        mMoveCallbacks.notifyStatusChanged(moveId,
16033                                PackageManager.MOVE_SUCCEEDED);
16034                        break;
16035                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16036                        mMoveCallbacks.notifyStatusChanged(moveId,
16037                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16038                        break;
16039                    default:
16040                        mMoveCallbacks.notifyStatusChanged(moveId,
16041                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16042                        break;
16043                }
16044            }
16045        };
16046
16047        final MoveInfo move;
16048        if (moveCompleteApp) {
16049            // Kick off a thread to report progress estimates
16050            new Thread() {
16051                @Override
16052                public void run() {
16053                    while (true) {
16054                        try {
16055                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16056                                break;
16057                            }
16058                        } catch (InterruptedException ignored) {
16059                        }
16060
16061                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16062                        final int progress = 10 + (int) MathUtils.constrain(
16063                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16064                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16065                    }
16066                }
16067            }.start();
16068
16069            final String dataAppName = codeFile.getName();
16070            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16071                    dataAppName, appId, seinfo);
16072        } else {
16073            move = null;
16074        }
16075
16076        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16077
16078        final Message msg = mHandler.obtainMessage(INIT_COPY);
16079        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16080        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16081                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16082        mHandler.sendMessage(msg);
16083    }
16084
16085    @Override
16086    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16088
16089        final int realMoveId = mNextMoveId.getAndIncrement();
16090        final Bundle extras = new Bundle();
16091        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16092        mMoveCallbacks.notifyCreated(realMoveId, extras);
16093
16094        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16095            @Override
16096            public void onCreated(int moveId, Bundle extras) {
16097                // Ignored
16098            }
16099
16100            @Override
16101            public void onStatusChanged(int moveId, int status, long estMillis) {
16102                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16103            }
16104        };
16105
16106        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16107        storage.setPrimaryStorageUuid(volumeUuid, callback);
16108        return realMoveId;
16109    }
16110
16111    @Override
16112    public int getMoveStatus(int moveId) {
16113        mContext.enforceCallingOrSelfPermission(
16114                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16115        return mMoveCallbacks.mLastStatus.get(moveId);
16116    }
16117
16118    @Override
16119    public void registerMoveCallback(IPackageMoveObserver callback) {
16120        mContext.enforceCallingOrSelfPermission(
16121                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16122        mMoveCallbacks.register(callback);
16123    }
16124
16125    @Override
16126    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16127        mContext.enforceCallingOrSelfPermission(
16128                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16129        mMoveCallbacks.unregister(callback);
16130    }
16131
16132    @Override
16133    public boolean setInstallLocation(int loc) {
16134        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16135                null);
16136        if (getInstallLocation() == loc) {
16137            return true;
16138        }
16139        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16140                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16141            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16142                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16143            return true;
16144        }
16145        return false;
16146   }
16147
16148    @Override
16149    public int getInstallLocation() {
16150        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16151                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16152                PackageHelper.APP_INSTALL_AUTO);
16153    }
16154
16155    /** Called by UserManagerService */
16156    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16157        mDirtyUsers.remove(userHandle);
16158        mSettings.removeUserLPw(userHandle);
16159        mPendingBroadcasts.remove(userHandle);
16160        if (mInstaller != null) {
16161            // Technically, we shouldn't be doing this with the package lock
16162            // held.  However, this is very rare, and there is already so much
16163            // other disk I/O going on, that we'll let it slide for now.
16164            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16165            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16166                final String volumeUuid = vol.getFsUuid();
16167                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16168                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16169            }
16170        }
16171        mUserNeedsBadging.delete(userHandle);
16172        removeUnusedPackagesLILPw(userManager, userHandle);
16173    }
16174
16175    /**
16176     * We're removing userHandle and would like to remove any downloaded packages
16177     * that are no longer in use by any other user.
16178     * @param userHandle the user being removed
16179     */
16180    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16181        final boolean DEBUG_CLEAN_APKS = false;
16182        int [] users = userManager.getUserIdsLPr();
16183        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16184        while (psit.hasNext()) {
16185            PackageSetting ps = psit.next();
16186            if (ps.pkg == null) {
16187                continue;
16188            }
16189            final String packageName = ps.pkg.packageName;
16190            // Skip over if system app
16191            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16192                continue;
16193            }
16194            if (DEBUG_CLEAN_APKS) {
16195                Slog.i(TAG, "Checking package " + packageName);
16196            }
16197            boolean keep = false;
16198            for (int i = 0; i < users.length; i++) {
16199                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16200                    keep = true;
16201                    if (DEBUG_CLEAN_APKS) {
16202                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16203                                + users[i]);
16204                    }
16205                    break;
16206                }
16207            }
16208            if (!keep) {
16209                if (DEBUG_CLEAN_APKS) {
16210                    Slog.i(TAG, "  Removing package " + packageName);
16211                }
16212                mHandler.post(new Runnable() {
16213                    public void run() {
16214                        deletePackageX(packageName, userHandle, 0);
16215                    } //end run
16216                });
16217            }
16218        }
16219    }
16220
16221    /** Called by UserManagerService */
16222    void createNewUserLILPw(int userHandle) {
16223        if (mInstaller != null) {
16224            mInstaller.createUserConfig(userHandle);
16225            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16226            applyFactoryDefaultBrowserLPw(userHandle);
16227            primeDomainVerificationsLPw(userHandle);
16228        }
16229    }
16230
16231    void newUserCreated(final int userHandle) {
16232        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16233    }
16234
16235    @Override
16236    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16237        mContext.enforceCallingOrSelfPermission(
16238                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16239                "Only package verification agents can read the verifier device identity");
16240
16241        synchronized (mPackages) {
16242            return mSettings.getVerifierDeviceIdentityLPw();
16243        }
16244    }
16245
16246    @Override
16247    public void setPermissionEnforced(String permission, boolean enforced) {
16248        // TODO: Now that we no longer change GID for storage, this should to away.
16249        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16250                "setPermissionEnforced");
16251        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16252            synchronized (mPackages) {
16253                if (mSettings.mReadExternalStorageEnforced == null
16254                        || mSettings.mReadExternalStorageEnforced != enforced) {
16255                    mSettings.mReadExternalStorageEnforced = enforced;
16256                    mSettings.writeLPr();
16257                }
16258            }
16259            // kill any non-foreground processes so we restart them and
16260            // grant/revoke the GID.
16261            final IActivityManager am = ActivityManagerNative.getDefault();
16262            if (am != null) {
16263                final long token = Binder.clearCallingIdentity();
16264                try {
16265                    am.killProcessesBelowForeground("setPermissionEnforcement");
16266                } catch (RemoteException e) {
16267                } finally {
16268                    Binder.restoreCallingIdentity(token);
16269                }
16270            }
16271        } else {
16272            throw new IllegalArgumentException("No selective enforcement for " + permission);
16273        }
16274    }
16275
16276    @Override
16277    @Deprecated
16278    public boolean isPermissionEnforced(String permission) {
16279        return true;
16280    }
16281
16282    @Override
16283    public boolean isStorageLow() {
16284        final long token = Binder.clearCallingIdentity();
16285        try {
16286            final DeviceStorageMonitorInternal
16287                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16288            if (dsm != null) {
16289                return dsm.isMemoryLow();
16290            } else {
16291                return false;
16292            }
16293        } finally {
16294            Binder.restoreCallingIdentity(token);
16295        }
16296    }
16297
16298    @Override
16299    public IPackageInstaller getPackageInstaller() {
16300        return mInstallerService;
16301    }
16302
16303    private boolean userNeedsBadging(int userId) {
16304        int index = mUserNeedsBadging.indexOfKey(userId);
16305        if (index < 0) {
16306            final UserInfo userInfo;
16307            final long token = Binder.clearCallingIdentity();
16308            try {
16309                userInfo = sUserManager.getUserInfo(userId);
16310            } finally {
16311                Binder.restoreCallingIdentity(token);
16312            }
16313            final boolean b;
16314            if (userInfo != null && userInfo.isManagedProfile()) {
16315                b = true;
16316            } else {
16317                b = false;
16318            }
16319            mUserNeedsBadging.put(userId, b);
16320            return b;
16321        }
16322        return mUserNeedsBadging.valueAt(index);
16323    }
16324
16325    @Override
16326    public KeySet getKeySetByAlias(String packageName, String alias) {
16327        if (packageName == null || alias == null) {
16328            return null;
16329        }
16330        synchronized(mPackages) {
16331            final PackageParser.Package pkg = mPackages.get(packageName);
16332            if (pkg == null) {
16333                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16334                throw new IllegalArgumentException("Unknown package: " + packageName);
16335            }
16336            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16337            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16338        }
16339    }
16340
16341    @Override
16342    public KeySet getSigningKeySet(String packageName) {
16343        if (packageName == null) {
16344            return null;
16345        }
16346        synchronized(mPackages) {
16347            final PackageParser.Package pkg = mPackages.get(packageName);
16348            if (pkg == null) {
16349                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16350                throw new IllegalArgumentException("Unknown package: " + packageName);
16351            }
16352            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16353                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16354                throw new SecurityException("May not access signing KeySet of other apps.");
16355            }
16356            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16357            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16358        }
16359    }
16360
16361    @Override
16362    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16363        if (packageName == null || ks == null) {
16364            return false;
16365        }
16366        synchronized(mPackages) {
16367            final PackageParser.Package pkg = mPackages.get(packageName);
16368            if (pkg == null) {
16369                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16370                throw new IllegalArgumentException("Unknown package: " + packageName);
16371            }
16372            IBinder ksh = ks.getToken();
16373            if (ksh instanceof KeySetHandle) {
16374                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16375                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16376            }
16377            return false;
16378        }
16379    }
16380
16381    @Override
16382    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16383        if (packageName == null || ks == null) {
16384            return false;
16385        }
16386        synchronized(mPackages) {
16387            final PackageParser.Package pkg = mPackages.get(packageName);
16388            if (pkg == null) {
16389                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16390                throw new IllegalArgumentException("Unknown package: " + packageName);
16391            }
16392            IBinder ksh = ks.getToken();
16393            if (ksh instanceof KeySetHandle) {
16394                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16395                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16396            }
16397            return false;
16398        }
16399    }
16400
16401    public void getUsageStatsIfNoPackageUsageInfo() {
16402        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16403            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16404            if (usm == null) {
16405                throw new IllegalStateException("UsageStatsManager must be initialized");
16406            }
16407            long now = System.currentTimeMillis();
16408            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16409            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16410                String packageName = entry.getKey();
16411                PackageParser.Package pkg = mPackages.get(packageName);
16412                if (pkg == null) {
16413                    continue;
16414                }
16415                UsageStats usage = entry.getValue();
16416                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16417                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16418            }
16419        }
16420    }
16421
16422    /**
16423     * Check and throw if the given before/after packages would be considered a
16424     * downgrade.
16425     */
16426    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16427            throws PackageManagerException {
16428        if (after.versionCode < before.mVersionCode) {
16429            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16430                    "Update version code " + after.versionCode + " is older than current "
16431                    + before.mVersionCode);
16432        } else if (after.versionCode == before.mVersionCode) {
16433            if (after.baseRevisionCode < before.baseRevisionCode) {
16434                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16435                        "Update base revision code " + after.baseRevisionCode
16436                        + " is older than current " + before.baseRevisionCode);
16437            }
16438
16439            if (!ArrayUtils.isEmpty(after.splitNames)) {
16440                for (int i = 0; i < after.splitNames.length; i++) {
16441                    final String splitName = after.splitNames[i];
16442                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16443                    if (j != -1) {
16444                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16445                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16446                                    "Update split " + splitName + " revision code "
16447                                    + after.splitRevisionCodes[i] + " is older than current "
16448                                    + before.splitRevisionCodes[j]);
16449                        }
16450                    }
16451                }
16452            }
16453        }
16454    }
16455
16456    private static class MoveCallbacks extends Handler {
16457        private static final int MSG_CREATED = 1;
16458        private static final int MSG_STATUS_CHANGED = 2;
16459
16460        private final RemoteCallbackList<IPackageMoveObserver>
16461                mCallbacks = new RemoteCallbackList<>();
16462
16463        private final SparseIntArray mLastStatus = new SparseIntArray();
16464
16465        public MoveCallbacks(Looper looper) {
16466            super(looper);
16467        }
16468
16469        public void register(IPackageMoveObserver callback) {
16470            mCallbacks.register(callback);
16471        }
16472
16473        public void unregister(IPackageMoveObserver callback) {
16474            mCallbacks.unregister(callback);
16475        }
16476
16477        @Override
16478        public void handleMessage(Message msg) {
16479            final SomeArgs args = (SomeArgs) msg.obj;
16480            final int n = mCallbacks.beginBroadcast();
16481            for (int i = 0; i < n; i++) {
16482                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16483                try {
16484                    invokeCallback(callback, msg.what, args);
16485                } catch (RemoteException ignored) {
16486                }
16487            }
16488            mCallbacks.finishBroadcast();
16489            args.recycle();
16490        }
16491
16492        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16493                throws RemoteException {
16494            switch (what) {
16495                case MSG_CREATED: {
16496                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16497                    break;
16498                }
16499                case MSG_STATUS_CHANGED: {
16500                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16501                    break;
16502                }
16503            }
16504        }
16505
16506        private void notifyCreated(int moveId, Bundle extras) {
16507            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16508
16509            final SomeArgs args = SomeArgs.obtain();
16510            args.argi1 = moveId;
16511            args.arg2 = extras;
16512            obtainMessage(MSG_CREATED, args).sendToTarget();
16513        }
16514
16515        private void notifyStatusChanged(int moveId, int status) {
16516            notifyStatusChanged(moveId, status, -1);
16517        }
16518
16519        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16520            Slog.v(TAG, "Move " + moveId + " status " + status);
16521
16522            final SomeArgs args = SomeArgs.obtain();
16523            args.argi1 = moveId;
16524            args.argi2 = status;
16525            args.arg3 = estMillis;
16526            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16527
16528            synchronized (mLastStatus) {
16529                mLastStatus.put(moveId, status);
16530            }
16531        }
16532    }
16533
16534    private final class OnPermissionChangeListeners extends Handler {
16535        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16536
16537        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16538                new RemoteCallbackList<>();
16539
16540        public OnPermissionChangeListeners(Looper looper) {
16541            super(looper);
16542        }
16543
16544        @Override
16545        public void handleMessage(Message msg) {
16546            switch (msg.what) {
16547                case MSG_ON_PERMISSIONS_CHANGED: {
16548                    final int uid = msg.arg1;
16549                    handleOnPermissionsChanged(uid);
16550                } break;
16551            }
16552        }
16553
16554        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16555            mPermissionListeners.register(listener);
16556
16557        }
16558
16559        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16560            mPermissionListeners.unregister(listener);
16561        }
16562
16563        public void onPermissionsChanged(int uid) {
16564            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16565                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16566            }
16567        }
16568
16569        private void handleOnPermissionsChanged(int uid) {
16570            final int count = mPermissionListeners.beginBroadcast();
16571            try {
16572                for (int i = 0; i < count; i++) {
16573                    IOnPermissionsChangeListener callback = mPermissionListeners
16574                            .getBroadcastItem(i);
16575                    try {
16576                        callback.onPermissionsChanged(uid);
16577                    } catch (RemoteException e) {
16578                        Log.e(TAG, "Permission listener is dead", e);
16579                    }
16580                }
16581            } finally {
16582                mPermissionListeners.finishBroadcast();
16583            }
16584        }
16585    }
16586
16587    private class PackageManagerInternalImpl extends PackageManagerInternal {
16588        @Override
16589        public void setLocationPackagesProvider(PackagesProvider provider) {
16590            synchronized (mPackages) {
16591                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16592            }
16593        }
16594
16595        @Override
16596        public void setImePackagesProvider(PackagesProvider provider) {
16597            synchronized (mPackages) {
16598                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16599            }
16600        }
16601
16602        @Override
16603        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16604            synchronized (mPackages) {
16605                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16606            }
16607        }
16608
16609        @Override
16610        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16611            synchronized (mPackages) {
16612                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16613            }
16614        }
16615
16616        @Override
16617        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16618            synchronized (mPackages) {
16619                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16620            }
16621        }
16622
16623        @Override
16624        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16625            synchronized (mPackages) {
16626                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16627            }
16628        }
16629
16630        @Override
16631        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16632            synchronized (mPackages) {
16633                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16634            }
16635        }
16636
16637        @Override
16638        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16639            synchronized (mPackages) {
16640                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16641                        packageName, userId);
16642            }
16643        }
16644
16645        @Override
16646        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16647            synchronized (mPackages) {
16648                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16649                        packageName, userId);
16650            }
16651        }
16652        @Override
16653        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16654            synchronized (mPackages) {
16655                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16656                        packageName, userId);
16657            }
16658        }
16659    }
16660
16661    @Override
16662    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16663        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16664        synchronized (mPackages) {
16665            final long identity = Binder.clearCallingIdentity();
16666            try {
16667                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16668                        packageNames, userId);
16669            } finally {
16670                Binder.restoreCallingIdentity(identity);
16671            }
16672        }
16673    }
16674
16675    private static void enforceSystemOrPhoneCaller(String tag) {
16676        int callingUid = Binder.getCallingUid();
16677        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16678            throw new SecurityException(
16679                    "Cannot call " + tag + " from UID " + callingUid);
16680        }
16681    }
16682}
16683