PackageManagerService.java revision a4911ed97102b638a373adcdae7e4c9b3c64cc30
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.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
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.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = false;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REQUIRE_KNOWN = 1<<12;
327    static final int SCAN_MOVE = 1<<13;
328    static final int SCAN_INITIAL = 1<<14;
329
330    static final int REMOVE_CHATTY = 1<<16;
331
332    private static final int[] EMPTY_INT_ARRAY = new int[0];
333
334    /**
335     * Timeout (in milliseconds) after which the watchdog should declare that
336     * our handler thread is wedged.  The usual default for such things is one
337     * minute but we sometimes do very lengthy I/O operations on this thread,
338     * such as installing multi-gigabyte applications, so ours needs to be longer.
339     */
340    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
341
342    /**
343     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
344     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
345     * settings entry if available, otherwise we use the hardcoded default.  If it's been
346     * more than this long since the last fstrim, we force one during the boot sequence.
347     *
348     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
349     * one gets run at the next available charging+idle time.  This final mandatory
350     * no-fstrim check kicks in only of the other scheduling criteria is never met.
351     */
352    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
353
354    /**
355     * Whether verification is enabled by default.
356     */
357    private static final boolean DEFAULT_VERIFY_ENABLE = true;
358
359    /**
360     * The default maximum time to wait for the verification agent to return in
361     * milliseconds.
362     */
363    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
364
365    /**
366     * The default response for package verification timeout.
367     *
368     * This can be either PackageManager.VERIFICATION_ALLOW or
369     * PackageManager.VERIFICATION_REJECT.
370     */
371    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
372
373    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
374
375    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
376            DEFAULT_CONTAINER_PACKAGE,
377            "com.android.defcontainer.DefaultContainerService");
378
379    private static final String KILL_APP_REASON_GIDS_CHANGED =
380            "permission grant or revoke changed gids";
381
382    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
383            "permissions revoked";
384
385    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
386
387    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
388
389    /** Permission grant: not grant the permission. */
390    private static final int GRANT_DENIED = 1;
391
392    /** Permission grant: grant the permission as an install permission. */
393    private static final int GRANT_INSTALL = 2;
394
395    /** Permission grant: grant the permission as an install permission for a legacy app. */
396    private static final int GRANT_INSTALL_LEGACY = 3;
397
398    /** Permission grant: grant the permission as a runtime one. */
399    private static final int GRANT_RUNTIME = 4;
400
401    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
402    private static final int GRANT_UPGRADE = 5;
403
404    /** Canonical intent used to identify what counts as a "web browser" app */
405    private static final Intent sBrowserIntent;
406    static {
407        sBrowserIntent = new Intent();
408        sBrowserIntent.setAction(Intent.ACTION_VIEW);
409        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
410        sBrowserIntent.setData(Uri.parse("http:"));
411    }
412
413    final ServiceThread mHandlerThread;
414
415    final PackageHandler mHandler;
416
417    /**
418     * Messages for {@link #mHandler} that need to wait for system ready before
419     * being dispatched.
420     */
421    private ArrayList<Message> mPostSystemReadyMessages;
422
423    final int mSdkVersion = Build.VERSION.SDK_INT;
424
425    final Context mContext;
426    final boolean mFactoryTest;
427    final boolean mOnlyCore;
428    final boolean mLazyDexOpt;
429    final long mDexOptLRUThresholdInMills;
430    final DisplayMetrics mMetrics;
431    final int mDefParseFlags;
432    final String[] mSeparateProcesses;
433    final boolean mIsUpgrade;
434
435    // This is where all application persistent data goes.
436    final File mAppDataDir;
437
438    // This is where all application persistent data goes for secondary users.
439    final File mUserAppDataDir;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451
452    /**
453     * Directory to which applications installed internally have their
454     * 32 bit native libraries copied.
455     */
456    private File mAppLib32InstallDir;
457
458    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
459    // apps.
460    final File mDrmAppPrivateInstallDir;
461
462    // ----------------------------------------------------------------
463
464    // Lock for state used when installing and doing other long running
465    // operations.  Methods that must be called with this lock held have
466    // the suffix "LI".
467    final Object mInstallLock = new Object();
468
469    // ----------------------------------------------------------------
470
471    // Keys are String (package name), values are Package.  This also serves
472    // as the lock for the global state.  Methods that must be called with
473    // this lock held have the prefix "LP".
474    @GuardedBy("mPackages")
475    final ArrayMap<String, PackageParser.Package> mPackages =
476            new ArrayMap<String, PackageParser.Package>();
477
478    // Tracks available target package names -> overlay package paths.
479    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
480        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
481
482    /**
483     * Tracks new system packages [receiving in an OTA] that we expect to
484     * find updated user-installed versions. Keys are package name, values
485     * are package location.
486     */
487    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
488
489    final Settings mSettings;
490    boolean mRestoredSettings;
491
492    // System configuration read by SystemConfig.
493    final int[] mGlobalGids;
494    final SparseArray<ArraySet<String>> mSystemPermissions;
495    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
496
497    // If mac_permissions.xml was found for seinfo labeling.
498    boolean mFoundPolicyFile;
499
500    // If a recursive restorecon of /data/data/<pkg> is needed.
501    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
502
503    public static final class SharedLibraryEntry {
504        public final String path;
505        public final String apk;
506
507        SharedLibraryEntry(String _path, String _apk) {
508            path = _path;
509            apk = _apk;
510        }
511    }
512
513    // Currently known shared libraries.
514    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
515            new ArrayMap<String, SharedLibraryEntry>();
516
517    // All available activities, for your resolving pleasure.
518    final ActivityIntentResolver mActivities =
519            new ActivityIntentResolver();
520
521    // All available receivers, for your resolving pleasure.
522    final ActivityIntentResolver mReceivers =
523            new ActivityIntentResolver();
524
525    // All available services, for your resolving pleasure.
526    final ServiceIntentResolver mServices = new ServiceIntentResolver();
527
528    // All available providers, for your resolving pleasure.
529    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
530
531    // Mapping from provider base names (first directory in content URI codePath)
532    // to the provider information.
533    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
534            new ArrayMap<String, PackageParser.Provider>();
535
536    // Mapping from instrumentation class names to info about them.
537    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
538            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
539
540    // Mapping from permission names to info about them.
541    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
542            new ArrayMap<String, PackageParser.PermissionGroup>();
543
544    // Packages whose data we have transfered into another package, thus
545    // should no longer exist.
546    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
547
548    // Broadcast actions that are only available to the system.
549    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
550
551    /** List of packages waiting for verification. */
552    final SparseArray<PackageVerificationState> mPendingVerification
553            = new SparseArray<PackageVerificationState>();
554
555    /** Set of packages associated with each app op permission. */
556    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
557
558    final PackageInstallerService mInstallerService;
559
560    private final PackageDexOptimizer mPackageDexOptimizer;
561
562    private AtomicInteger mNextMoveId = new AtomicInteger();
563    private final MoveCallbacks mMoveCallbacks;
564
565    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
566
567    // Cache of users who need badging.
568    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
569
570    /** Token for keys in mPendingVerification. */
571    private int mPendingVerificationToken = 0;
572
573    volatile boolean mSystemReady;
574    volatile boolean mSafeMode;
575    volatile boolean mHasSystemUidErrors;
576
577    ApplicationInfo mAndroidApplication;
578    final ActivityInfo mResolveActivity = new ActivityInfo();
579    final ResolveInfo mResolveInfo = new ResolveInfo();
580    ComponentName mResolveComponentName;
581    PackageParser.Package mPlatformPackage;
582    ComponentName mCustomResolverComponentName;
583
584    boolean mResolverReplaced = false;
585
586    private final ComponentName mIntentFilterVerifierComponent;
587    private int mIntentFilterVerificationToken = 0;
588
589    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
590            = new SparseArray<IntentFilterVerificationState>();
591
592    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
593            new DefaultPermissionGrantPolicy(this);
594
595    private static class IFVerificationParams {
596        PackageParser.Package pkg;
597        boolean replacing;
598        int userId;
599        int verifierUid;
600
601        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
602                int _userId, int _verifierUid) {
603            pkg = _pkg;
604            replacing = _replacing;
605            userId = _userId;
606            replacing = _replacing;
607            verifierUid = _verifierUid;
608        }
609    }
610
611    private interface IntentFilterVerifier<T extends IntentFilter> {
612        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
613                                               T filter, String packageName);
614        void startVerifications(int userId);
615        void receiveVerificationResponse(int verificationId);
616    }
617
618    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
619        private Context mContext;
620        private ComponentName mIntentFilterVerifierComponent;
621        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
622
623        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
624            mContext = context;
625            mIntentFilterVerifierComponent = verifierComponent;
626        }
627
628        private String getDefaultScheme() {
629            return IntentFilter.SCHEME_HTTPS;
630        }
631
632        @Override
633        public void startVerifications(int userId) {
634            // Launch verifications requests
635            int count = mCurrentIntentFilterVerifications.size();
636            for (int n=0; n<count; n++) {
637                int verificationId = mCurrentIntentFilterVerifications.get(n);
638                final IntentFilterVerificationState ivs =
639                        mIntentFilterVerificationStates.get(verificationId);
640
641                String packageName = ivs.getPackageName();
642
643                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
644                final int filterCount = filters.size();
645                ArraySet<String> domainsSet = new ArraySet<>();
646                for (int m=0; m<filterCount; m++) {
647                    PackageParser.ActivityIntentInfo filter = filters.get(m);
648                    domainsSet.addAll(filter.getHostsList());
649                }
650                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
651                synchronized (mPackages) {
652                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
653                            packageName, domainsList) != null) {
654                        scheduleWriteSettingsLocked();
655                    }
656                }
657                sendVerificationRequest(userId, verificationId, ivs);
658            }
659            mCurrentIntentFilterVerifications.clear();
660        }
661
662        private void sendVerificationRequest(int userId, int verificationId,
663                IntentFilterVerificationState ivs) {
664
665            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
668                    verificationId);
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
671                    getDefaultScheme());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
674                    ivs.getHostsString());
675            verificationIntent.putExtra(
676                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
677                    ivs.getPackageName());
678            verificationIntent.setComponent(mIntentFilterVerifierComponent);
679            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680
681            UserHandle user = new UserHandle(userId);
682            mContext.sendBroadcastAsUser(verificationIntent, user);
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Sending IntentFilter verification broadcast");
685        }
686
687        public void receiveVerificationResponse(int verificationId) {
688            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
689
690            final boolean verified = ivs.isVerified();
691
692            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
693            final int count = filters.size();
694            if (DEBUG_DOMAIN_VERIFICATION) {
695                Slog.i(TAG, "Received verification response " + verificationId
696                        + " for " + count + " filters, verified=" + verified);
697            }
698            for (int n=0; n<count; n++) {
699                PackageParser.ActivityIntentInfo filter = filters.get(n);
700                filter.setVerified(verified);
701
702                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
703                        + " verified with result:" + verified + " and hosts:"
704                        + ivs.getHostsString());
705            }
706
707            mIntentFilterVerificationStates.remove(verificationId);
708
709            final String packageName = ivs.getPackageName();
710            IntentFilterVerificationInfo ivi = null;
711
712            synchronized (mPackages) {
713                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
714            }
715            if (ivi == null) {
716                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
717                        + verificationId + " packageName:" + packageName);
718                return;
719            }
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Updating IntentFilterVerificationInfo for package " + packageName
722                            +" verificationId:" + verificationId);
723
724            synchronized (mPackages) {
725                if (verified) {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
727                } else {
728                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
729                }
730                scheduleWriteSettingsLocked();
731
732                final int userId = ivs.getUserId();
733                if (userId != UserHandle.USER_ALL) {
734                    final int userStatus =
735                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
736
737                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
738                    boolean needUpdate = false;
739
740                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
741                    // already been set by the User thru the Disambiguation dialog
742                    switch (userStatus) {
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                            } else {
747                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
748                            }
749                            needUpdate = true;
750                            break;
751
752                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
753                            if (verified) {
754                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
755                                needUpdate = true;
756                            }
757                            break;
758
759                        default:
760                            // Nothing to do
761                    }
762
763                    if (needUpdate) {
764                        mSettings.updateIntentFilterVerificationStatusLPw(
765                                packageName, updatedStatus, userId);
766                        scheduleWritePackageRestrictionsLocked(userId);
767                    }
768                }
769            }
770        }
771
772        @Override
773        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
774                    ActivityIntentInfo filter, String packageName) {
775            if (!hasValidDomains(filter)) {
776                return false;
777            }
778            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
779            if (ivs == null) {
780                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
781                        packageName);
782            }
783            if (DEBUG_DOMAIN_VERIFICATION) {
784                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
785            }
786            ivs.addFilter(filter);
787            return true;
788        }
789
790        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
791                int userId, int verificationId, String packageName) {
792            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
793                    verifierUid, userId, packageName);
794            ivs.setPendingState();
795            synchronized (mPackages) {
796                mIntentFilterVerificationStates.append(verificationId, ivs);
797                mCurrentIntentFilterVerifications.add(verificationId);
798            }
799            return ivs;
800        }
801    }
802
803    private static boolean hasValidDomains(ActivityIntentInfo filter) {
804        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
805                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
806                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
807    }
808
809    private IntentFilterVerifier mIntentFilterVerifier;
810
811    // Set of pending broadcasts for aggregating enable/disable of components.
812    static class PendingPackageBroadcasts {
813        // for each user id, a map of <package name -> components within that package>
814        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
815
816        public PendingPackageBroadcasts() {
817            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
818        }
819
820        public ArrayList<String> get(int userId, String packageName) {
821            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822            return packages.get(packageName);
823        }
824
825        public void put(int userId, String packageName, ArrayList<String> components) {
826            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
827            packages.put(packageName, components);
828        }
829
830        public void remove(int userId, String packageName) {
831            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
832            if (packages != null) {
833                packages.remove(packageName);
834            }
835        }
836
837        public void remove(int userId) {
838            mUidMap.remove(userId);
839        }
840
841        public int userIdCount() {
842            return mUidMap.size();
843        }
844
845        public int userIdAt(int n) {
846            return mUidMap.keyAt(n);
847        }
848
849        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
850            return mUidMap.get(userId);
851        }
852
853        public int size() {
854            // total number of pending broadcast entries across all userIds
855            int num = 0;
856            for (int i = 0; i< mUidMap.size(); i++) {
857                num += mUidMap.valueAt(i).size();
858            }
859            return num;
860        }
861
862        public void clear() {
863            mUidMap.clear();
864        }
865
866        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
867            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
868            if (map == null) {
869                map = new ArrayMap<String, ArrayList<String>>();
870                mUidMap.put(userId, map);
871            }
872            return map;
873        }
874    }
875    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
876
877    // Service Connection to remote media container service to copy
878    // package uri's from external media onto secure containers
879    // or internal storage.
880    private IMediaContainerService mContainerService = null;
881
882    static final int SEND_PENDING_BROADCAST = 1;
883    static final int MCS_BOUND = 3;
884    static final int END_COPY = 4;
885    static final int INIT_COPY = 5;
886    static final int MCS_UNBIND = 6;
887    static final int START_CLEANING_PACKAGE = 7;
888    static final int FIND_INSTALL_LOC = 8;
889    static final int POST_INSTALL = 9;
890    static final int MCS_RECONNECT = 10;
891    static final int MCS_GIVE_UP = 11;
892    static final int UPDATED_MEDIA_STATUS = 12;
893    static final int WRITE_SETTINGS = 13;
894    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
895    static final int PACKAGE_VERIFIED = 15;
896    static final int CHECK_PENDING_VERIFICATION = 16;
897    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
898    static final int INTENT_FILTER_VERIFIED = 18;
899
900    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
901
902    // Delay time in millisecs
903    static final int BROADCAST_DELAY = 10 * 1000;
904
905    static UserManagerService sUserManager;
906
907    // Stores a list of users whose package restrictions file needs to be updated
908    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
909
910    final private DefaultContainerConnection mDefContainerConn =
911            new DefaultContainerConnection();
912    class DefaultContainerConnection implements ServiceConnection {
913        public void onServiceConnected(ComponentName name, IBinder service) {
914            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
915            IMediaContainerService imcs =
916                IMediaContainerService.Stub.asInterface(service);
917            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
918        }
919
920        public void onServiceDisconnected(ComponentName name) {
921            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
922        }
923    }
924
925    // Recordkeeping of restore-after-install operations that are currently in flight
926    // between the Package Manager and the Backup Manager
927    class PostInstallData {
928        public InstallArgs args;
929        public PackageInstalledInfo res;
930
931        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
932            args = _a;
933            res = _r;
934        }
935    }
936
937    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
938    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
939
940    // XML tags for backup/restore of various bits of state
941    private static final String TAG_PREFERRED_BACKUP = "pa";
942    private static final String TAG_DEFAULT_APPS = "da";
943    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
944
945    final String mRequiredVerifierPackage;
946    final String mRequiredInstallerPackage;
947
948    private final PackageUsage mPackageUsage = new PackageUsage();
949
950    private class PackageUsage {
951        private static final int WRITE_INTERVAL
952            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
953
954        private final Object mFileLock = new Object();
955        private final AtomicLong mLastWritten = new AtomicLong(0);
956        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
957
958        private boolean mIsHistoricalPackageUsageAvailable = true;
959
960        boolean isHistoricalPackageUsageAvailable() {
961            return mIsHistoricalPackageUsageAvailable;
962        }
963
964        void write(boolean force) {
965            if (force) {
966                writeInternal();
967                return;
968            }
969            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
970                && !DEBUG_DEXOPT) {
971                return;
972            }
973            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
974                new Thread("PackageUsage_DiskWriter") {
975                    @Override
976                    public void run() {
977                        try {
978                            writeInternal();
979                        } finally {
980                            mBackgroundWriteRunning.set(false);
981                        }
982                    }
983                }.start();
984            }
985        }
986
987        private void writeInternal() {
988            synchronized (mPackages) {
989                synchronized (mFileLock) {
990                    AtomicFile file = getFile();
991                    FileOutputStream f = null;
992                    try {
993                        f = file.startWrite();
994                        BufferedOutputStream out = new BufferedOutputStream(f);
995                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
996                        StringBuilder sb = new StringBuilder();
997                        for (PackageParser.Package pkg : mPackages.values()) {
998                            if (pkg.mLastPackageUsageTimeInMills == 0) {
999                                continue;
1000                            }
1001                            sb.setLength(0);
1002                            sb.append(pkg.packageName);
1003                            sb.append(' ');
1004                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1005                            sb.append('\n');
1006                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1007                        }
1008                        out.flush();
1009                        file.finishWrite(f);
1010                    } catch (IOException e) {
1011                        if (f != null) {
1012                            file.failWrite(f);
1013                        }
1014                        Log.e(TAG, "Failed to write package usage times", e);
1015                    }
1016                }
1017            }
1018            mLastWritten.set(SystemClock.elapsedRealtime());
1019        }
1020
1021        void readLP() {
1022            synchronized (mFileLock) {
1023                AtomicFile file = getFile();
1024                BufferedInputStream in = null;
1025                try {
1026                    in = new BufferedInputStream(file.openRead());
1027                    StringBuffer sb = new StringBuffer();
1028                    while (true) {
1029                        String packageName = readToken(in, sb, ' ');
1030                        if (packageName == null) {
1031                            break;
1032                        }
1033                        String timeInMillisString = readToken(in, sb, '\n');
1034                        if (timeInMillisString == null) {
1035                            throw new IOException("Failed to find last usage time for package "
1036                                                  + packageName);
1037                        }
1038                        PackageParser.Package pkg = mPackages.get(packageName);
1039                        if (pkg == null) {
1040                            continue;
1041                        }
1042                        long timeInMillis;
1043                        try {
1044                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1045                        } catch (NumberFormatException e) {
1046                            throw new IOException("Failed to parse " + timeInMillisString
1047                                                  + " as a long.", e);
1048                        }
1049                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1050                    }
1051                } catch (FileNotFoundException expected) {
1052                    mIsHistoricalPackageUsageAvailable = false;
1053                } catch (IOException e) {
1054                    Log.w(TAG, "Failed to read package usage times", e);
1055                } finally {
1056                    IoUtils.closeQuietly(in);
1057                }
1058            }
1059            mLastWritten.set(SystemClock.elapsedRealtime());
1060        }
1061
1062        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1063                throws IOException {
1064            sb.setLength(0);
1065            while (true) {
1066                int ch = in.read();
1067                if (ch == -1) {
1068                    if (sb.length() == 0) {
1069                        return null;
1070                    }
1071                    throw new IOException("Unexpected EOF");
1072                }
1073                if (ch == endOfToken) {
1074                    return sb.toString();
1075                }
1076                sb.append((char)ch);
1077            }
1078        }
1079
1080        private AtomicFile getFile() {
1081            File dataDir = Environment.getDataDirectory();
1082            File systemDir = new File(dataDir, "system");
1083            File fname = new File(systemDir, "package-usage.list");
1084            return new AtomicFile(fname);
1085        }
1086    }
1087
1088    class PackageHandler extends Handler {
1089        private boolean mBound = false;
1090        final ArrayList<HandlerParams> mPendingInstalls =
1091            new ArrayList<HandlerParams>();
1092
1093        private boolean connectToService() {
1094            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1095                    " DefaultContainerService");
1096            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1099                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1100                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1101                mBound = true;
1102                return true;
1103            }
1104            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105            return false;
1106        }
1107
1108        private void disconnectService() {
1109            mContainerService = null;
1110            mBound = false;
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112            mContext.unbindService(mDefContainerConn);
1113            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114        }
1115
1116        PackageHandler(Looper looper) {
1117            super(looper);
1118        }
1119
1120        public void handleMessage(Message msg) {
1121            try {
1122                doHandleMessage(msg);
1123            } finally {
1124                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125            }
1126        }
1127
1128        void doHandleMessage(Message msg) {
1129            switch (msg.what) {
1130                case INIT_COPY: {
1131                    HandlerParams params = (HandlerParams) msg.obj;
1132                    int idx = mPendingInstalls.size();
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1134                    // If a bind was already initiated we dont really
1135                    // need to do anything. The pending install
1136                    // will be processed later on.
1137                    if (!mBound) {
1138                        // If this is the only one pending we might
1139                        // have to bind to the service again.
1140                        if (!connectToService()) {
1141                            Slog.e(TAG, "Failed to bind to media container service");
1142                            params.serviceError();
1143                            return;
1144                        } else {
1145                            // Once we bind to the service, the first
1146                            // pending request will be processed.
1147                            mPendingInstalls.add(idx, params);
1148                        }
1149                    } else {
1150                        mPendingInstalls.add(idx, params);
1151                        // Already bound to the service. Just make
1152                        // sure we trigger off processing the first request.
1153                        if (idx == 0) {
1154                            mHandler.sendEmptyMessage(MCS_BOUND);
1155                        }
1156                    }
1157                    break;
1158                }
1159                case MCS_BOUND: {
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1161                    if (msg.obj != null) {
1162                        mContainerService = (IMediaContainerService) msg.obj;
1163                    }
1164                    if (mContainerService == null) {
1165                        if (!mBound) {
1166                            // Something seriously wrong since we are not bound and we are not
1167                            // waiting for connection. Bail out.
1168                            Slog.e(TAG, "Cannot bind to media container service");
1169                            for (HandlerParams params : mPendingInstalls) {
1170                                // Indicate service bind error
1171                                params.serviceError();
1172                            }
1173                            mPendingInstalls.clear();
1174                        } else {
1175                            Slog.w(TAG, "Waiting to connect to media container service");
1176                        }
1177                    } else if (mPendingInstalls.size() > 0) {
1178                        HandlerParams params = mPendingInstalls.get(0);
1179                        if (params != null) {
1180                            if (params.startCopy()) {
1181                                // We are done...  look for more work or to
1182                                // go idle.
1183                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1184                                        "Checking for more work or unbind...");
1185                                // Delete pending install
1186                                if (mPendingInstalls.size() > 0) {
1187                                    mPendingInstalls.remove(0);
1188                                }
1189                                if (mPendingInstalls.size() == 0) {
1190                                    if (mBound) {
1191                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1192                                                "Posting delayed MCS_UNBIND");
1193                                        removeMessages(MCS_UNBIND);
1194                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1195                                        // Unbind after a little delay, to avoid
1196                                        // continual thrashing.
1197                                        sendMessageDelayed(ubmsg, 10000);
1198                                    }
1199                                } else {
1200                                    // There are more pending requests in queue.
1201                                    // Just post MCS_BOUND message to trigger processing
1202                                    // of next pending install.
1203                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                            "Posting MCS_BOUND for next work");
1205                                    mHandler.sendEmptyMessage(MCS_BOUND);
1206                                }
1207                            }
1208                        }
1209                    } else {
1210                        // Should never happen ideally.
1211                        Slog.w(TAG, "Empty queue");
1212                    }
1213                    break;
1214                }
1215                case MCS_RECONNECT: {
1216                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1217                    if (mPendingInstalls.size() > 0) {
1218                        if (mBound) {
1219                            disconnectService();
1220                        }
1221                        if (!connectToService()) {
1222                            Slog.e(TAG, "Failed to bind to media container service");
1223                            for (HandlerParams params : mPendingInstalls) {
1224                                // Indicate service bind error
1225                                params.serviceError();
1226                            }
1227                            mPendingInstalls.clear();
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_UNBIND: {
1233                    // If there is no actual work left, then time to unbind.
1234                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1235
1236                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1237                        if (mBound) {
1238                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1239
1240                            disconnectService();
1241                        }
1242                    } else if (mPendingInstalls.size() > 0) {
1243                        // There are more pending requests in queue.
1244                        // Just post MCS_BOUND message to trigger processing
1245                        // of next pending install.
1246                        mHandler.sendEmptyMessage(MCS_BOUND);
1247                    }
1248
1249                    break;
1250                }
1251                case MCS_GIVE_UP: {
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1253                    mPendingInstalls.remove(0);
1254                    break;
1255                }
1256                case SEND_PENDING_BROADCAST: {
1257                    String packages[];
1258                    ArrayList<String> components[];
1259                    int size = 0;
1260                    int uids[];
1261                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262                    synchronized (mPackages) {
1263                        if (mPendingBroadcasts == null) {
1264                            return;
1265                        }
1266                        size = mPendingBroadcasts.size();
1267                        if (size <= 0) {
1268                            // Nothing to be done. Just return
1269                            return;
1270                        }
1271                        packages = new String[size];
1272                        components = new ArrayList[size];
1273                        uids = new int[size];
1274                        int i = 0;  // filling out the above arrays
1275
1276                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1277                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1278                            Iterator<Map.Entry<String, ArrayList<String>>> it
1279                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1280                                            .entrySet().iterator();
1281                            while (it.hasNext() && i < size) {
1282                                Map.Entry<String, ArrayList<String>> ent = it.next();
1283                                packages[i] = ent.getKey();
1284                                components[i] = ent.getValue();
1285                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1286                                uids[i] = (ps != null)
1287                                        ? UserHandle.getUid(packageUserId, ps.appId)
1288                                        : -1;
1289                                i++;
1290                            }
1291                        }
1292                        size = i;
1293                        mPendingBroadcasts.clear();
1294                    }
1295                    // Send broadcasts
1296                    for (int i = 0; i < size; i++) {
1297                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1298                    }
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300                    break;
1301                }
1302                case START_CLEANING_PACKAGE: {
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1304                    final String packageName = (String)msg.obj;
1305                    final int userId = msg.arg1;
1306                    final boolean andCode = msg.arg2 != 0;
1307                    synchronized (mPackages) {
1308                        if (userId == UserHandle.USER_ALL) {
1309                            int[] users = sUserManager.getUserIds();
1310                            for (int user : users) {
1311                                mSettings.addPackageToCleanLPw(
1312                                        new PackageCleanItem(user, packageName, andCode));
1313                            }
1314                        } else {
1315                            mSettings.addPackageToCleanLPw(
1316                                    new PackageCleanItem(userId, packageName, andCode));
1317                        }
1318                    }
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                    startCleaningPackages();
1321                } break;
1322                case POST_INSTALL: {
1323                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1324                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1325                    mRunningInstalls.delete(msg.arg1);
1326                    boolean deleteOld = false;
1327
1328                    if (data != null) {
1329                        InstallArgs args = data.args;
1330                        PackageInstalledInfo res = data.res;
1331
1332                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1333                            final String packageName = res.pkg.applicationInfo.packageName;
1334                            res.removedInfo.sendBroadcast(false, true, false);
1335                            Bundle extras = new Bundle(1);
1336                            extras.putInt(Intent.EXTRA_UID, res.uid);
1337
1338                            // Now that we successfully installed the package, grant runtime
1339                            // permissions if requested before broadcasting the install.
1340                            if ((args.installFlags
1341                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1342                                grantRequestedRuntimePermissions(res.pkg,
1343                                        args.user.getIdentifier());
1344                            }
1345
1346                            // Determine the set of users who are adding this
1347                            // package for the first time vs. those who are seeing
1348                            // an update.
1349                            int[] firstUsers;
1350                            int[] updateUsers = new int[0];
1351                            if (res.origUsers == null || res.origUsers.length == 0) {
1352                                firstUsers = res.newUsers;
1353                            } else {
1354                                firstUsers = new int[0];
1355                                for (int i=0; i<res.newUsers.length; i++) {
1356                                    int user = res.newUsers[i];
1357                                    boolean isNew = true;
1358                                    for (int j=0; j<res.origUsers.length; j++) {
1359                                        if (res.origUsers[j] == user) {
1360                                            isNew = false;
1361                                            break;
1362                                        }
1363                                    }
1364                                    if (isNew) {
1365                                        int[] newFirst = new int[firstUsers.length+1];
1366                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1367                                                firstUsers.length);
1368                                        newFirst[firstUsers.length] = user;
1369                                        firstUsers = newFirst;
1370                                    } else {
1371                                        int[] newUpdate = new int[updateUsers.length+1];
1372                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1373                                                updateUsers.length);
1374                                        newUpdate[updateUsers.length] = user;
1375                                        updateUsers = newUpdate;
1376                                    }
1377                                }
1378                            }
1379                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                    packageName, extras, null, null, firstUsers);
1381                            final boolean update = res.removedInfo.removedPackage != null;
1382                            if (update) {
1383                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1384                            }
1385                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1386                                    packageName, extras, null, null, updateUsers);
1387                            if (update) {
1388                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1389                                        packageName, extras, null, null, updateUsers);
1390                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1391                                        null, null, packageName, null, updateUsers);
1392
1393                                // treat asec-hosted packages like removable media on upgrade
1394                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1395                                    if (DEBUG_INSTALL) {
1396                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1397                                                + " is ASEC-hosted -> AVAILABLE");
1398                                    }
1399                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1400                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1401                                    pkgList.add(packageName);
1402                                    sendResourcesChangedBroadcast(true, true,
1403                                            pkgList,uidArray, null);
1404                                }
1405                            }
1406                            if (res.removedInfo.args != null) {
1407                                // Remove the replaced package's older resources safely now
1408                                deleteOld = true;
1409                            }
1410
1411                            // If this app is a browser and it's newly-installed for some
1412                            // users, clear any default-browser state in those users
1413                            if (firstUsers.length > 0) {
1414                                // the app's nature doesn't depend on the user, so we can just
1415                                // check its browser nature in any user and generalize.
1416                                if (packageIsBrowser(packageName, firstUsers[0])) {
1417                                    synchronized (mPackages) {
1418                                        for (int userId : firstUsers) {
1419                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1420                                        }
1421                                    }
1422                                }
1423                            }
1424                            // Log current value of "unknown sources" setting
1425                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1426                                getUnknownSourcesSettings());
1427                        }
1428                        // Force a gc to clear up things
1429                        Runtime.getRuntime().gc();
1430                        // We delete after a gc for applications  on sdcard.
1431                        if (deleteOld) {
1432                            synchronized (mInstallLock) {
1433                                res.removedInfo.args.doPostDeleteLI(true);
1434                            }
1435                        }
1436                        if (args.observer != null) {
1437                            try {
1438                                Bundle extras = extrasForInstallResult(res);
1439                                args.observer.onPackageInstalled(res.name, res.returnCode,
1440                                        res.returnMsg, extras);
1441                            } catch (RemoteException e) {
1442                                Slog.i(TAG, "Observer no longer exists.");
1443                            }
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448                } break;
1449                case UPDATED_MEDIA_STATUS: {
1450                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1451                    boolean reportStatus = msg.arg1 == 1;
1452                    boolean doGc = msg.arg2 == 1;
1453                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1454                    if (doGc) {
1455                        // Force a gc to clear up stale containers.
1456                        Runtime.getRuntime().gc();
1457                    }
1458                    if (msg.obj != null) {
1459                        @SuppressWarnings("unchecked")
1460                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1461                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1462                        // Unload containers
1463                        unloadAllContainers(args);
1464                    }
1465                    if (reportStatus) {
1466                        try {
1467                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1468                            PackageHelper.getMountService().finishMediaUpdate();
1469                        } catch (RemoteException e) {
1470                            Log.e(TAG, "MountService not running?");
1471                        }
1472                    }
1473                } break;
1474                case WRITE_SETTINGS: {
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476                    synchronized (mPackages) {
1477                        removeMessages(WRITE_SETTINGS);
1478                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                        mSettings.writeLPr();
1480                        mDirtyUsers.clear();
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                } break;
1484                case WRITE_PACKAGE_RESTRICTIONS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                        for (int userId : mDirtyUsers) {
1489                            mSettings.writePackageRestrictionsLPr(userId);
1490                        }
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case CHECK_PENDING_VERIFICATION: {
1496                    final int verificationId = msg.arg1;
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                    if ((state != null) && !state.timeoutExtended()) {
1500                        final InstallArgs args = state.getInstallArgs();
1501                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                        Slog.i(TAG, "Verification timed out for " + originUri);
1504                        mPendingVerification.remove(verificationId);
1505
1506                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                            Slog.i(TAG, "Continuing with installation of " + originUri);
1510                            state.setVerifierResponse(Binder.getCallingUid(),
1511                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_ALLOW,
1514                                    state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            broadcastPackageVerified(verificationId, originUri,
1522                                    PackageManager.VERIFICATION_REJECT,
1523                                    state.getInstallArgs().getUser());
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527                        mHandler.sendEmptyMessage(MCS_UNBIND);
1528                    }
1529                    break;
1530                }
1531                case PACKAGE_VERIFIED: {
1532                    final int verificationId = msg.arg1;
1533
1534                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1535                    if (state == null) {
1536                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1537                        break;
1538                    }
1539
1540                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1541
1542                    state.setVerifierResponse(response.callerUid, response.code);
1543
1544                    if (state.isVerificationComplete()) {
1545                        mPendingVerification.remove(verificationId);
1546
1547                        final InstallArgs args = state.getInstallArgs();
1548                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                        int ret;
1551                        if (state.isInstallAllowed()) {
1552                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1553                            broadcastPackageVerified(verificationId, originUri,
1554                                    response.code, state.getInstallArgs().getUser());
1555                            try {
1556                                ret = args.copyApk(mContainerService, true);
1557                            } catch (RemoteException e) {
1558                                Slog.e(TAG, "Could not contact the ContainerService");
1559                            }
1560                        } else {
1561                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1562                        }
1563
1564                        processPendingInstall(args, ret);
1565
1566                        mHandler.sendEmptyMessage(MCS_UNBIND);
1567                    }
1568
1569                    break;
1570                }
1571                case START_INTENT_FILTER_VERIFICATIONS: {
1572                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                            params.replacing, params.pkg);
1575                    break;
1576                }
1577                case INTENT_FILTER_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                            verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final int userId = state.getUserId();
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "Processing IntentFilter verification with token:"
1592                            + verificationId + " and userId:" + userId);
1593
1594                    final IntentFilterVerificationResponse response =
1595                            (IntentFilterVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                            "IntentFilter verification with token:" + verificationId
1601                            + " and userId:" + userId
1602                            + " is settings verifier response with response code:"
1603                            + response.code);
1604
1605                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                + response.getFailedDomainsString());
1608                    }
1609
1610                    if (state.isVerificationComplete()) {
1611                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                    } else {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                "IntentFilter verification with token:" + verificationId
1615                                + " was not said to be complete");
1616                    }
1617
1618                    break;
1619                }
1620            }
1621        }
1622    }
1623
1624    private StorageEventListener mStorageListener = new StorageEventListener() {
1625        @Override
1626        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1627            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1628                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1629                    final String volumeUuid = vol.getFsUuid();
1630
1631                    // Clean up any users or apps that were removed or recreated
1632                    // while this volume was missing
1633                    reconcileUsers(volumeUuid);
1634                    reconcileApps(volumeUuid);
1635
1636                    // Clean up any install sessions that expired or were
1637                    // cancelled while this volume was missing
1638                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1639
1640                    loadPrivatePackages(vol);
1641
1642                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1643                    unloadPrivatePackages(vol);
1644                }
1645            }
1646
1647            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1648                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1649                    updateExternalMediaStatus(true, false);
1650                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1651                    updateExternalMediaStatus(false, false);
1652                }
1653            }
1654        }
1655
1656        @Override
1657        public void onVolumeForgotten(String fsUuid) {
1658            // Remove any apps installed on the forgotten volume
1659            synchronized (mPackages) {
1660                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1661                for (PackageSetting ps : packages) {
1662                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1663                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1664                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1665                }
1666
1667                mSettings.writeLPr();
1668            }
1669        }
1670    };
1671
1672    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1673        if (userId >= UserHandle.USER_OWNER) {
1674            grantRequestedRuntimePermissionsForUser(pkg, userId);
1675        } else if (userId == UserHandle.USER_ALL) {
1676            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1677                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1678            }
1679        }
1680
1681        // We could have touched GID membership, so flush out packages.list
1682        synchronized (mPackages) {
1683            mSettings.writePackageListLPr();
1684        }
1685    }
1686
1687    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1688        SettingBase sb = (SettingBase) pkg.mExtras;
1689        if (sb == null) {
1690            return;
1691        }
1692
1693        PermissionsState permissionsState = sb.getPermissionsState();
1694
1695        for (String permission : pkg.requestedPermissions) {
1696            BasePermission bp = mSettings.mPermissions.get(permission);
1697            if (bp != null && bp.isRuntime()) {
1698                permissionsState.grantRuntimePermission(bp, userId);
1699            }
1700        }
1701    }
1702
1703    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1704        Bundle extras = null;
1705        switch (res.returnCode) {
1706            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1707                extras = new Bundle();
1708                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1709                        res.origPermission);
1710                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1711                        res.origPackage);
1712                break;
1713            }
1714            case PackageManager.INSTALL_SUCCEEDED: {
1715                extras = new Bundle();
1716                extras.putBoolean(Intent.EXTRA_REPLACING,
1717                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1718                break;
1719            }
1720        }
1721        return extras;
1722    }
1723
1724    void scheduleWriteSettingsLocked() {
1725        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1726            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1727        }
1728    }
1729
1730    void scheduleWritePackageRestrictionsLocked(int userId) {
1731        if (!sUserManager.exists(userId)) return;
1732        mDirtyUsers.add(userId);
1733        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1734            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1735        }
1736    }
1737
1738    public static PackageManagerService main(Context context, Installer installer,
1739            boolean factoryTest, boolean onlyCore) {
1740        PackageManagerService m = new PackageManagerService(context, installer,
1741                factoryTest, onlyCore);
1742        ServiceManager.addService("package", m);
1743        return m;
1744    }
1745
1746    static String[] splitString(String str, char sep) {
1747        int count = 1;
1748        int i = 0;
1749        while ((i=str.indexOf(sep, i)) >= 0) {
1750            count++;
1751            i++;
1752        }
1753
1754        String[] res = new String[count];
1755        i=0;
1756        count = 0;
1757        int lastI=0;
1758        while ((i=str.indexOf(sep, i)) >= 0) {
1759            res[count] = str.substring(lastI, i);
1760            count++;
1761            i++;
1762            lastI = i;
1763        }
1764        res[count] = str.substring(lastI, str.length());
1765        return res;
1766    }
1767
1768    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1769        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1770                Context.DISPLAY_SERVICE);
1771        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1772    }
1773
1774    public PackageManagerService(Context context, Installer installer,
1775            boolean factoryTest, boolean onlyCore) {
1776        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1777                SystemClock.uptimeMillis());
1778
1779        if (mSdkVersion <= 0) {
1780            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1781        }
1782
1783        mContext = context;
1784        mFactoryTest = factoryTest;
1785        mOnlyCore = onlyCore;
1786        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1787        mMetrics = new DisplayMetrics();
1788        mSettings = new Settings(mPackages);
1789        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1790                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1791        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1792                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1793        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1794                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1796                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1797        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1798                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1799        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1800                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1801
1802        // TODO: add a property to control this?
1803        long dexOptLRUThresholdInMinutes;
1804        if (mLazyDexOpt) {
1805            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1806        } else {
1807            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1808        }
1809        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1810
1811        String separateProcesses = SystemProperties.get("debug.separate_processes");
1812        if (separateProcesses != null && separateProcesses.length() > 0) {
1813            if ("*".equals(separateProcesses)) {
1814                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1815                mSeparateProcesses = null;
1816                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1817            } else {
1818                mDefParseFlags = 0;
1819                mSeparateProcesses = separateProcesses.split(",");
1820                Slog.w(TAG, "Running with debug.separate_processes: "
1821                        + separateProcesses);
1822            }
1823        } else {
1824            mDefParseFlags = 0;
1825            mSeparateProcesses = null;
1826        }
1827
1828        mInstaller = installer;
1829        mPackageDexOptimizer = new PackageDexOptimizer(this);
1830        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1831
1832        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1833                FgThread.get().getLooper());
1834
1835        getDefaultDisplayMetrics(context, mMetrics);
1836
1837        SystemConfig systemConfig = SystemConfig.getInstance();
1838        mGlobalGids = systemConfig.getGlobalGids();
1839        mSystemPermissions = systemConfig.getSystemPermissions();
1840        mAvailableFeatures = systemConfig.getAvailableFeatures();
1841
1842        synchronized (mInstallLock) {
1843        // writer
1844        synchronized (mPackages) {
1845            mHandlerThread = new ServiceThread(TAG,
1846                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1847            mHandlerThread.start();
1848            mHandler = new PackageHandler(mHandlerThread.getLooper());
1849            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1850
1851            File dataDir = Environment.getDataDirectory();
1852            mAppDataDir = new File(dataDir, "data");
1853            mAppInstallDir = new File(dataDir, "app");
1854            mAppLib32InstallDir = new File(dataDir, "app-lib");
1855            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1856            mUserAppDataDir = new File(dataDir, "user");
1857            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1858
1859            sUserManager = new UserManagerService(context, this,
1860                    mInstallLock, mPackages);
1861
1862            // Propagate permission configuration in to package manager.
1863            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1864                    = systemConfig.getPermissions();
1865            for (int i=0; i<permConfig.size(); i++) {
1866                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1867                BasePermission bp = mSettings.mPermissions.get(perm.name);
1868                if (bp == null) {
1869                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1870                    mSettings.mPermissions.put(perm.name, bp);
1871                }
1872                if (perm.gids != null) {
1873                    bp.setGids(perm.gids, perm.perUser);
1874                }
1875            }
1876
1877            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1878            for (int i=0; i<libConfig.size(); i++) {
1879                mSharedLibraries.put(libConfig.keyAt(i),
1880                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1881            }
1882
1883            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1884
1885            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1886                    mSdkVersion, mOnlyCore);
1887
1888            String customResolverActivity = Resources.getSystem().getString(
1889                    R.string.config_customResolverActivity);
1890            if (TextUtils.isEmpty(customResolverActivity)) {
1891                customResolverActivity = null;
1892            } else {
1893                mCustomResolverComponentName = ComponentName.unflattenFromString(
1894                        customResolverActivity);
1895            }
1896
1897            long startTime = SystemClock.uptimeMillis();
1898
1899            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1900                    startTime);
1901
1902            // Set flag to monitor and not change apk file paths when
1903            // scanning install directories.
1904            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1905
1906            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1907
1908            /**
1909             * Add everything in the in the boot class path to the
1910             * list of process files because dexopt will have been run
1911             * if necessary during zygote startup.
1912             */
1913            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1914            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1915
1916            if (bootClassPath != null) {
1917                String[] bootClassPathElements = splitString(bootClassPath, ':');
1918                for (String element : bootClassPathElements) {
1919                    alreadyDexOpted.add(element);
1920                }
1921            } else {
1922                Slog.w(TAG, "No BOOTCLASSPATH found!");
1923            }
1924
1925            if (systemServerClassPath != null) {
1926                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1927                for (String element : systemServerClassPathElements) {
1928                    alreadyDexOpted.add(element);
1929                }
1930            } else {
1931                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1932            }
1933
1934            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1935            final String[] dexCodeInstructionSets =
1936                    getDexCodeInstructionSets(
1937                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1938
1939            /**
1940             * Ensure all external libraries have had dexopt run on them.
1941             */
1942            if (mSharedLibraries.size() > 0) {
1943                // NOTE: For now, we're compiling these system "shared libraries"
1944                // (and framework jars) into all available architectures. It's possible
1945                // to compile them only when we come across an app that uses them (there's
1946                // already logic for that in scanPackageLI) but that adds some complexity.
1947                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1948                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1949                        final String lib = libEntry.path;
1950                        if (lib == null) {
1951                            continue;
1952                        }
1953
1954                        try {
1955                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1956                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1957                                alreadyDexOpted.add(lib);
1958                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1959                            }
1960                        } catch (FileNotFoundException e) {
1961                            Slog.w(TAG, "Library not found: " + lib);
1962                        } catch (IOException e) {
1963                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1964                                    + e.getMessage());
1965                        }
1966                    }
1967                }
1968            }
1969
1970            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1971
1972            // Gross hack for now: we know this file doesn't contain any
1973            // code, so don't dexopt it to avoid the resulting log spew.
1974            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1975
1976            // Gross hack for now: we know this file is only part of
1977            // the boot class path for art, so don't dexopt it to
1978            // avoid the resulting log spew.
1979            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1980
1981            /**
1982             * There are a number of commands implemented in Java, which
1983             * we currently need to do the dexopt on so that they can be
1984             * run from a non-root shell.
1985             */
1986            String[] frameworkFiles = frameworkDir.list();
1987            if (frameworkFiles != null) {
1988                // TODO: We could compile these only for the most preferred ABI. We should
1989                // first double check that the dex files for these commands are not referenced
1990                // by other system apps.
1991                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1992                    for (int i=0; i<frameworkFiles.length; i++) {
1993                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1994                        String path = libPath.getPath();
1995                        // Skip the file if we already did it.
1996                        if (alreadyDexOpted.contains(path)) {
1997                            continue;
1998                        }
1999                        // Skip the file if it is not a type we want to dexopt.
2000                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2001                            continue;
2002                        }
2003                        try {
2004                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2005                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2006                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2007                            }
2008                        } catch (FileNotFoundException e) {
2009                            Slog.w(TAG, "Jar not found: " + path);
2010                        } catch (IOException e) {
2011                            Slog.w(TAG, "Exception reading jar: " + path, e);
2012                        }
2013                    }
2014                }
2015            }
2016
2017            // Collect vendor overlay packages.
2018            // (Do this before scanning any apps.)
2019            // For security and version matching reason, only consider
2020            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2021            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2022            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2023                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2024
2025            // Find base frameworks (resource packages without code).
2026            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2027                    | PackageParser.PARSE_IS_SYSTEM_DIR
2028                    | PackageParser.PARSE_IS_PRIVILEGED,
2029                    scanFlags | SCAN_NO_DEX, 0);
2030
2031            // Collected privileged system packages.
2032            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2033            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR
2035                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2036
2037            // Collect ordinary system packages.
2038            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2039            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2041
2042            // Collect all vendor packages.
2043            File vendorAppDir = new File("/vendor/app");
2044            try {
2045                vendorAppDir = vendorAppDir.getCanonicalFile();
2046            } catch (IOException e) {
2047                // failed to look up canonical path, continue with original one
2048            }
2049            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2050                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2051
2052            // Collect all OEM packages.
2053            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2054            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2055                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2056
2057            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2058            mInstaller.moveFiles();
2059
2060            // Prune any system packages that no longer exist.
2061            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2062            if (!mOnlyCore) {
2063                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2064                while (psit.hasNext()) {
2065                    PackageSetting ps = psit.next();
2066
2067                    /*
2068                     * If this is not a system app, it can't be a
2069                     * disable system app.
2070                     */
2071                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2072                        continue;
2073                    }
2074
2075                    /*
2076                     * If the package is scanned, it's not erased.
2077                     */
2078                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2079                    if (scannedPkg != null) {
2080                        /*
2081                         * If the system app is both scanned and in the
2082                         * disabled packages list, then it must have been
2083                         * added via OTA. Remove it from the currently
2084                         * scanned package so the previously user-installed
2085                         * application can be scanned.
2086                         */
2087                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2088                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2089                                    + ps.name + "; removing system app.  Last known codePath="
2090                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2091                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2092                                    + scannedPkg.mVersionCode);
2093                            removePackageLI(ps, true);
2094                            mExpectingBetter.put(ps.name, ps.codePath);
2095                        }
2096
2097                        continue;
2098                    }
2099
2100                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                        psit.remove();
2102                        logCriticalInfo(Log.WARN, "System package " + ps.name
2103                                + " no longer exists; wiping its data");
2104                        removeDataDirsLI(null, ps.name);
2105                    } else {
2106                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2107                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2108                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2109                        }
2110                    }
2111                }
2112            }
2113
2114            //look for any incomplete package installations
2115            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2116            //clean up list
2117            for(int i = 0; i < deletePkgsList.size(); i++) {
2118                //clean up here
2119                cleanupInstallFailedPackage(deletePkgsList.get(i));
2120            }
2121            //delete tmp files
2122            deleteTempPackageFiles();
2123
2124            // Remove any shared userIDs that have no associated packages
2125            mSettings.pruneSharedUsersLPw();
2126
2127            if (!mOnlyCore) {
2128                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2129                        SystemClock.uptimeMillis());
2130                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2131
2132                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2133                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2134
2135                /**
2136                 * Remove disable package settings for any updated system
2137                 * apps that were removed via an OTA. If they're not a
2138                 * previously-updated app, remove them completely.
2139                 * Otherwise, just revoke their system-level permissions.
2140                 */
2141                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2142                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2143                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2144
2145                    String msg;
2146                    if (deletedPkg == null) {
2147                        msg = "Updated system package " + deletedAppName
2148                                + " no longer exists; wiping its data";
2149                        removeDataDirsLI(null, deletedAppName);
2150                    } else {
2151                        msg = "Updated system app + " + deletedAppName
2152                                + " no longer present; removing system privileges for "
2153                                + deletedAppName;
2154
2155                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2156
2157                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2158                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2159                    }
2160                    logCriticalInfo(Log.WARN, msg);
2161                }
2162
2163                /**
2164                 * Make sure all system apps that we expected to appear on
2165                 * the userdata partition actually showed up. If they never
2166                 * appeared, crawl back and revive the system version.
2167                 */
2168                for (int i = 0; i < mExpectingBetter.size(); i++) {
2169                    final String packageName = mExpectingBetter.keyAt(i);
2170                    if (!mPackages.containsKey(packageName)) {
2171                        final File scanFile = mExpectingBetter.valueAt(i);
2172
2173                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2174                                + " but never showed up; reverting to system");
2175
2176                        final int reparseFlags;
2177                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2178                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2179                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2180                                    | PackageParser.PARSE_IS_PRIVILEGED;
2181                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2182                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2183                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2184                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2185                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2186                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2187                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2188                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2189                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2190                        } else {
2191                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2192                            continue;
2193                        }
2194
2195                        mSettings.enableSystemPackageLPw(packageName);
2196
2197                        try {
2198                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2199                        } catch (PackageManagerException e) {
2200                            Slog.e(TAG, "Failed to parse original system package: "
2201                                    + e.getMessage());
2202                        }
2203                    }
2204                }
2205            }
2206            mExpectingBetter.clear();
2207
2208            // Now that we know all of the shared libraries, update all clients to have
2209            // the correct library paths.
2210            updateAllSharedLibrariesLPw();
2211
2212            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2213                // NOTE: We ignore potential failures here during a system scan (like
2214                // the rest of the commands above) because there's precious little we
2215                // can do about it. A settings error is reported, though.
2216                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2217                        false /* force dexopt */, false /* defer dexopt */);
2218            }
2219
2220            // Now that we know all the packages we are keeping,
2221            // read and update their last usage times.
2222            mPackageUsage.readLP();
2223
2224            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2225                    SystemClock.uptimeMillis());
2226            Slog.i(TAG, "Time to scan packages: "
2227                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2228                    + " seconds");
2229
2230            // If the platform SDK has changed since the last time we booted,
2231            // we need to re-grant app permission to catch any new ones that
2232            // appear.  This is really a hack, and means that apps can in some
2233            // cases get permissions that the user didn't initially explicitly
2234            // allow...  it would be nice to have some better way to handle
2235            // this situation.
2236            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2237                    != mSdkVersion;
2238            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2239                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2240                    + "; regranting permissions for internal storage");
2241            mSettings.mInternalSdkPlatform = mSdkVersion;
2242
2243            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2244                    | (regrantPermissions
2245                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2246                            : 0));
2247
2248            // If this is the first boot, and it is a normal boot, then
2249            // we need to initialize the default preferred apps.
2250            if (!mRestoredSettings && !onlyCore) {
2251                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2252                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2253                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2254            }
2255
2256            // If this is first boot after an OTA, and a normal boot, then
2257            // we need to clear code cache directories.
2258            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2259            if (mIsUpgrade && !onlyCore) {
2260                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2261                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2262                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2263                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2264                }
2265                mSettings.mFingerprint = Build.FINGERPRINT;
2266            }
2267
2268            checkDefaultBrowser();
2269
2270            // All the changes are done during package scanning.
2271            mSettings.updateInternalDatabaseVersion();
2272
2273            // can downgrade to reader
2274            mSettings.writeLPr();
2275
2276            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2277                    SystemClock.uptimeMillis());
2278
2279            mRequiredVerifierPackage = getRequiredVerifierLPr();
2280            mRequiredInstallerPackage = getRequiredInstallerLPr();
2281
2282            mInstallerService = new PackageInstallerService(context, this);
2283
2284            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2285            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2286                    mIntentFilterVerifierComponent);
2287
2288        } // synchronized (mPackages)
2289        } // synchronized (mInstallLock)
2290
2291        // Now after opening every single application zip, make sure they
2292        // are all flushed.  Not really needed, but keeps things nice and
2293        // tidy.
2294        Runtime.getRuntime().gc();
2295
2296        // Expose private service for system components to use.
2297        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2298    }
2299
2300    @Override
2301    public boolean isFirstBoot() {
2302        return !mRestoredSettings;
2303    }
2304
2305    @Override
2306    public boolean isOnlyCoreApps() {
2307        return mOnlyCore;
2308    }
2309
2310    @Override
2311    public boolean isUpgrade() {
2312        return mIsUpgrade;
2313    }
2314
2315    private String getRequiredVerifierLPr() {
2316        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2317        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2318                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2319
2320        String requiredVerifier = null;
2321
2322        final int N = receivers.size();
2323        for (int i = 0; i < N; i++) {
2324            final ResolveInfo info = receivers.get(i);
2325
2326            if (info.activityInfo == null) {
2327                continue;
2328            }
2329
2330            final String packageName = info.activityInfo.packageName;
2331
2332            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2333                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2334                continue;
2335            }
2336
2337            if (requiredVerifier != null) {
2338                throw new RuntimeException("There can be only one required verifier");
2339            }
2340
2341            requiredVerifier = packageName;
2342        }
2343
2344        return requiredVerifier;
2345    }
2346
2347    private String getRequiredInstallerLPr() {
2348        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2349        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2350        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2351
2352        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2353                PACKAGE_MIME_TYPE, 0, 0);
2354
2355        String requiredInstaller = null;
2356
2357        final int N = installers.size();
2358        for (int i = 0; i < N; i++) {
2359            final ResolveInfo info = installers.get(i);
2360            final String packageName = info.activityInfo.packageName;
2361
2362            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2363                continue;
2364            }
2365
2366            if (requiredInstaller != null) {
2367                throw new RuntimeException("There must be one required installer");
2368            }
2369
2370            requiredInstaller = packageName;
2371        }
2372
2373        if (requiredInstaller == null) {
2374            throw new RuntimeException("There must be one required installer");
2375        }
2376
2377        return requiredInstaller;
2378    }
2379
2380    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2381        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2382        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2383                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2384
2385        ComponentName verifierComponentName = null;
2386
2387        int priority = -1000;
2388        final int N = receivers.size();
2389        for (int i = 0; i < N; i++) {
2390            final ResolveInfo info = receivers.get(i);
2391
2392            if (info.activityInfo == null) {
2393                continue;
2394            }
2395
2396            final String packageName = info.activityInfo.packageName;
2397
2398            final PackageSetting ps = mSettings.mPackages.get(packageName);
2399            if (ps == null) {
2400                continue;
2401            }
2402
2403            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2404                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2405                continue;
2406            }
2407
2408            // Select the IntentFilterVerifier with the highest priority
2409            if (priority < info.priority) {
2410                priority = info.priority;
2411                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2412                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2413                        + verifierComponentName + " with priority: " + info.priority);
2414            }
2415        }
2416
2417        return verifierComponentName;
2418    }
2419
2420    private void primeDomainVerificationsLPw(int userId) {
2421        if (DEBUG_DOMAIN_VERIFICATION) {
2422            Slog.d(TAG, "Priming domain verifications in user " + userId);
2423        }
2424
2425        SystemConfig systemConfig = SystemConfig.getInstance();
2426        ArraySet<String> packages = systemConfig.getLinkedApps();
2427        ArraySet<String> domains = new ArraySet<String>();
2428
2429        for (String packageName : packages) {
2430            PackageParser.Package pkg = mPackages.get(packageName);
2431            if (pkg != null) {
2432                if (!pkg.isSystemApp()) {
2433                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2434                    continue;
2435                }
2436
2437                domains.clear();
2438                for (PackageParser.Activity a : pkg.activities) {
2439                    for (ActivityIntentInfo filter : a.intents) {
2440                        if (hasValidDomains(filter)) {
2441                            domains.addAll(filter.getHostsList());
2442                        }
2443                    }
2444                }
2445
2446                if (domains.size() > 0) {
2447                    if (DEBUG_DOMAIN_VERIFICATION) {
2448                        Slog.v(TAG, "      + " + packageName);
2449                    }
2450                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2451                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2452                    // and then 'always' in the per-user state actually used for intent resolution.
2453                    final IntentFilterVerificationInfo ivi;
2454                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2455                            new ArrayList<String>(domains));
2456                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2457                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2458                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2459                } else {
2460                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2461                            + "' does not handle web links");
2462                }
2463            } else {
2464                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2465            }
2466        }
2467
2468        scheduleWritePackageRestrictionsLocked(userId);
2469        scheduleWriteSettingsLocked();
2470    }
2471
2472    private void applyFactoryDefaultBrowserLPw(int userId) {
2473        // The default browser app's package name is stored in a string resource,
2474        // with a product-specific overlay used for vendor customization.
2475        String browserPkg = mContext.getResources().getString(
2476                com.android.internal.R.string.default_browser);
2477        if (!TextUtils.isEmpty(browserPkg)) {
2478            // non-empty string => required to be a known package
2479            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2480            if (ps == null) {
2481                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2482                browserPkg = null;
2483            } else {
2484                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2485            }
2486        }
2487
2488        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2489        // default.  If there's more than one, just leave everything alone.
2490        if (browserPkg == null) {
2491            calculateDefaultBrowserLPw(userId);
2492        }
2493    }
2494
2495    private void calculateDefaultBrowserLPw(int userId) {
2496        List<String> allBrowsers = resolveAllBrowserApps(userId);
2497        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2498        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499    }
2500
2501    private List<String> resolveAllBrowserApps(int userId) {
2502        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2503        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2504                PackageManager.MATCH_ALL, userId);
2505
2506        final int count = list.size();
2507        List<String> result = new ArrayList<String>(count);
2508        for (int i=0; i<count; i++) {
2509            ResolveInfo info = list.get(i);
2510            if (info.activityInfo == null
2511                    || !info.handleAllWebDataURI
2512                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2513                    || result.contains(info.activityInfo.packageName)) {
2514                continue;
2515            }
2516            result.add(info.activityInfo.packageName);
2517        }
2518
2519        return result;
2520    }
2521
2522    private boolean packageIsBrowser(String packageName, int userId) {
2523        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2524                PackageManager.MATCH_ALL, userId);
2525        final int N = list.size();
2526        for (int i = 0; i < N; i++) {
2527            ResolveInfo info = list.get(i);
2528            if (packageName.equals(info.activityInfo.packageName)) {
2529                return true;
2530            }
2531        }
2532        return false;
2533    }
2534
2535    private void checkDefaultBrowser() {
2536        final int myUserId = UserHandle.myUserId();
2537        final String packageName = getDefaultBrowserPackageName(myUserId);
2538        if (packageName != null) {
2539            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2540            if (info == null) {
2541                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2542                synchronized (mPackages) {
2543                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2544                }
2545            }
2546        }
2547    }
2548
2549    @Override
2550    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2551            throws RemoteException {
2552        try {
2553            return super.onTransact(code, data, reply, flags);
2554        } catch (RuntimeException e) {
2555            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2556                Slog.wtf(TAG, "Package Manager Crash", e);
2557            }
2558            throw e;
2559        }
2560    }
2561
2562    void cleanupInstallFailedPackage(PackageSetting ps) {
2563        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2564
2565        removeDataDirsLI(ps.volumeUuid, ps.name);
2566        if (ps.codePath != null) {
2567            if (ps.codePath.isDirectory()) {
2568                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2569            } else {
2570                ps.codePath.delete();
2571            }
2572        }
2573        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2574            if (ps.resourcePath.isDirectory()) {
2575                FileUtils.deleteContents(ps.resourcePath);
2576            }
2577            ps.resourcePath.delete();
2578        }
2579        mSettings.removePackageLPw(ps.name);
2580    }
2581
2582    static int[] appendInts(int[] cur, int[] add) {
2583        if (add == null) return cur;
2584        if (cur == null) return add;
2585        final int N = add.length;
2586        for (int i=0; i<N; i++) {
2587            cur = appendInt(cur, add[i]);
2588        }
2589        return cur;
2590    }
2591
2592    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2593        if (!sUserManager.exists(userId)) return null;
2594        final PackageSetting ps = (PackageSetting) p.mExtras;
2595        if (ps == null) {
2596            return null;
2597        }
2598
2599        final PermissionsState permissionsState = ps.getPermissionsState();
2600
2601        final int[] gids = permissionsState.computeGids(userId);
2602        final Set<String> permissions = permissionsState.getPermissions(userId);
2603        final PackageUserState state = ps.readUserState(userId);
2604
2605        return PackageParser.generatePackageInfo(p, gids, flags,
2606                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2607    }
2608
2609    @Override
2610    public boolean isPackageFrozen(String packageName) {
2611        synchronized (mPackages) {
2612            final PackageSetting ps = mSettings.mPackages.get(packageName);
2613            if (ps != null) {
2614                return ps.frozen;
2615            }
2616        }
2617        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2618        return true;
2619    }
2620
2621    @Override
2622    public boolean isPackageAvailable(String packageName, int userId) {
2623        if (!sUserManager.exists(userId)) return false;
2624        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2625        synchronized (mPackages) {
2626            PackageParser.Package p = mPackages.get(packageName);
2627            if (p != null) {
2628                final PackageSetting ps = (PackageSetting) p.mExtras;
2629                if (ps != null) {
2630                    final PackageUserState state = ps.readUserState(userId);
2631                    if (state != null) {
2632                        return PackageParser.isAvailable(state);
2633                    }
2634                }
2635            }
2636        }
2637        return false;
2638    }
2639
2640    @Override
2641    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2642        if (!sUserManager.exists(userId)) return null;
2643        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2644        // reader
2645        synchronized (mPackages) {
2646            PackageParser.Package p = mPackages.get(packageName);
2647            if (DEBUG_PACKAGE_INFO)
2648                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2649            if (p != null) {
2650                return generatePackageInfo(p, flags, userId);
2651            }
2652            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2653                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2654            }
2655        }
2656        return null;
2657    }
2658
2659    @Override
2660    public String[] currentToCanonicalPackageNames(String[] names) {
2661        String[] out = new String[names.length];
2662        // reader
2663        synchronized (mPackages) {
2664            for (int i=names.length-1; i>=0; i--) {
2665                PackageSetting ps = mSettings.mPackages.get(names[i]);
2666                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2667            }
2668        }
2669        return out;
2670    }
2671
2672    @Override
2673    public String[] canonicalToCurrentPackageNames(String[] names) {
2674        String[] out = new String[names.length];
2675        // reader
2676        synchronized (mPackages) {
2677            for (int i=names.length-1; i>=0; i--) {
2678                String cur = mSettings.mRenamedPackages.get(names[i]);
2679                out[i] = cur != null ? cur : names[i];
2680            }
2681        }
2682        return out;
2683    }
2684
2685    @Override
2686    public int getPackageUid(String packageName, int userId) {
2687        if (!sUserManager.exists(userId)) return -1;
2688        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2689
2690        // reader
2691        synchronized (mPackages) {
2692            PackageParser.Package p = mPackages.get(packageName);
2693            if(p != null) {
2694                return UserHandle.getUid(userId, p.applicationInfo.uid);
2695            }
2696            PackageSetting ps = mSettings.mPackages.get(packageName);
2697            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2698                return -1;
2699            }
2700            p = ps.pkg;
2701            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2702        }
2703    }
2704
2705    @Override
2706    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2707        if (!sUserManager.exists(userId)) {
2708            return null;
2709        }
2710
2711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2712                "getPackageGids");
2713
2714        // reader
2715        synchronized (mPackages) {
2716            PackageParser.Package p = mPackages.get(packageName);
2717            if (DEBUG_PACKAGE_INFO) {
2718                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2719            }
2720            if (p != null) {
2721                PackageSetting ps = (PackageSetting) p.mExtras;
2722                return ps.getPermissionsState().computeGids(userId);
2723            }
2724        }
2725
2726        return null;
2727    }
2728
2729    static PermissionInfo generatePermissionInfo(
2730            BasePermission bp, int flags) {
2731        if (bp.perm != null) {
2732            return PackageParser.generatePermissionInfo(bp.perm, flags);
2733        }
2734        PermissionInfo pi = new PermissionInfo();
2735        pi.name = bp.name;
2736        pi.packageName = bp.sourcePackage;
2737        pi.nonLocalizedLabel = bp.name;
2738        pi.protectionLevel = bp.protectionLevel;
2739        return pi;
2740    }
2741
2742    @Override
2743    public PermissionInfo getPermissionInfo(String name, int flags) {
2744        // reader
2745        synchronized (mPackages) {
2746            final BasePermission p = mSettings.mPermissions.get(name);
2747            if (p != null) {
2748                return generatePermissionInfo(p, flags);
2749            }
2750            return null;
2751        }
2752    }
2753
2754    @Override
2755    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2756        // reader
2757        synchronized (mPackages) {
2758            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2759            for (BasePermission p : mSettings.mPermissions.values()) {
2760                if (group == null) {
2761                    if (p.perm == null || p.perm.info.group == null) {
2762                        out.add(generatePermissionInfo(p, flags));
2763                    }
2764                } else {
2765                    if (p.perm != null && group.equals(p.perm.info.group)) {
2766                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2767                    }
2768                }
2769            }
2770
2771            if (out.size() > 0) {
2772                return out;
2773            }
2774            return mPermissionGroups.containsKey(group) ? out : null;
2775        }
2776    }
2777
2778    @Override
2779    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2780        // reader
2781        synchronized (mPackages) {
2782            return PackageParser.generatePermissionGroupInfo(
2783                    mPermissionGroups.get(name), flags);
2784        }
2785    }
2786
2787    @Override
2788    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2789        // reader
2790        synchronized (mPackages) {
2791            final int N = mPermissionGroups.size();
2792            ArrayList<PermissionGroupInfo> out
2793                    = new ArrayList<PermissionGroupInfo>(N);
2794            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2795                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2796            }
2797            return out;
2798        }
2799    }
2800
2801    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2802            int userId) {
2803        if (!sUserManager.exists(userId)) return null;
2804        PackageSetting ps = mSettings.mPackages.get(packageName);
2805        if (ps != null) {
2806            if (ps.pkg == null) {
2807                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2808                        flags, userId);
2809                if (pInfo != null) {
2810                    return pInfo.applicationInfo;
2811                }
2812                return null;
2813            }
2814            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2815                    ps.readUserState(userId), userId);
2816        }
2817        return null;
2818    }
2819
2820    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2821            int userId) {
2822        if (!sUserManager.exists(userId)) return null;
2823        PackageSetting ps = mSettings.mPackages.get(packageName);
2824        if (ps != null) {
2825            PackageParser.Package pkg = ps.pkg;
2826            if (pkg == null) {
2827                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2828                    return null;
2829                }
2830                // Only data remains, so we aren't worried about code paths
2831                pkg = new PackageParser.Package(packageName);
2832                pkg.applicationInfo.packageName = packageName;
2833                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2834                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2835                pkg.applicationInfo.dataDir = Environment
2836                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2837                        .getAbsolutePath();
2838                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2839                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2840            }
2841            return generatePackageInfo(pkg, flags, userId);
2842        }
2843        return null;
2844    }
2845
2846    @Override
2847    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2848        if (!sUserManager.exists(userId)) return null;
2849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2850        // writer
2851        synchronized (mPackages) {
2852            PackageParser.Package p = mPackages.get(packageName);
2853            if (DEBUG_PACKAGE_INFO) Log.v(
2854                    TAG, "getApplicationInfo " + packageName
2855                    + ": " + p);
2856            if (p != null) {
2857                PackageSetting ps = mSettings.mPackages.get(packageName);
2858                if (ps == null) return null;
2859                // Note: isEnabledLP() does not apply here - always return info
2860                return PackageParser.generateApplicationInfo(
2861                        p, flags, ps.readUserState(userId), userId);
2862            }
2863            if ("android".equals(packageName)||"system".equals(packageName)) {
2864                return mAndroidApplication;
2865            }
2866            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2867                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2868            }
2869        }
2870        return null;
2871    }
2872
2873    @Override
2874    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2875            final IPackageDataObserver observer) {
2876        mContext.enforceCallingOrSelfPermission(
2877                android.Manifest.permission.CLEAR_APP_CACHE, null);
2878        // Queue up an async operation since clearing cache may take a little while.
2879        mHandler.post(new Runnable() {
2880            public void run() {
2881                mHandler.removeCallbacks(this);
2882                int retCode = -1;
2883                synchronized (mInstallLock) {
2884                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2885                    if (retCode < 0) {
2886                        Slog.w(TAG, "Couldn't clear application caches");
2887                    }
2888                }
2889                if (observer != null) {
2890                    try {
2891                        observer.onRemoveCompleted(null, (retCode >= 0));
2892                    } catch (RemoteException e) {
2893                        Slog.w(TAG, "RemoveException when invoking call back");
2894                    }
2895                }
2896            }
2897        });
2898    }
2899
2900    @Override
2901    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2902            final IntentSender pi) {
2903        mContext.enforceCallingOrSelfPermission(
2904                android.Manifest.permission.CLEAR_APP_CACHE, null);
2905        // Queue up an async operation since clearing cache may take a little while.
2906        mHandler.post(new Runnable() {
2907            public void run() {
2908                mHandler.removeCallbacks(this);
2909                int retCode = -1;
2910                synchronized (mInstallLock) {
2911                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2912                    if (retCode < 0) {
2913                        Slog.w(TAG, "Couldn't clear application caches");
2914                    }
2915                }
2916                if(pi != null) {
2917                    try {
2918                        // Callback via pending intent
2919                        int code = (retCode >= 0) ? 1 : 0;
2920                        pi.sendIntent(null, code, null,
2921                                null, null);
2922                    } catch (SendIntentException e1) {
2923                        Slog.i(TAG, "Failed to send pending intent");
2924                    }
2925                }
2926            }
2927        });
2928    }
2929
2930    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2931        synchronized (mInstallLock) {
2932            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2933                throw new IOException("Failed to free enough space");
2934            }
2935        }
2936    }
2937
2938    @Override
2939    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2940        if (!sUserManager.exists(userId)) return null;
2941        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2942        synchronized (mPackages) {
2943            PackageParser.Activity a = mActivities.mActivities.get(component);
2944
2945            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2946            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2947                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2948                if (ps == null) return null;
2949                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2950                        userId);
2951            }
2952            if (mResolveComponentName.equals(component)) {
2953                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2954                        new PackageUserState(), userId);
2955            }
2956        }
2957        return null;
2958    }
2959
2960    @Override
2961    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2962            String resolvedType) {
2963        synchronized (mPackages) {
2964            PackageParser.Activity a = mActivities.mActivities.get(component);
2965            if (a == null) {
2966                return false;
2967            }
2968            for (int i=0; i<a.intents.size(); i++) {
2969                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2970                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2971                    return true;
2972                }
2973            }
2974            return false;
2975        }
2976    }
2977
2978    @Override
2979    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2980        if (!sUserManager.exists(userId)) return null;
2981        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2982        synchronized (mPackages) {
2983            PackageParser.Activity a = mReceivers.mActivities.get(component);
2984            if (DEBUG_PACKAGE_INFO) Log.v(
2985                TAG, "getReceiverInfo " + component + ": " + a);
2986            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2987                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2988                if (ps == null) return null;
2989                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2990                        userId);
2991            }
2992        }
2993        return null;
2994    }
2995
2996    @Override
2997    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2998        if (!sUserManager.exists(userId)) return null;
2999        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3000        synchronized (mPackages) {
3001            PackageParser.Service s = mServices.mServices.get(component);
3002            if (DEBUG_PACKAGE_INFO) Log.v(
3003                TAG, "getServiceInfo " + component + ": " + s);
3004            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3006                if (ps == null) return null;
3007                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3008                        userId);
3009            }
3010        }
3011        return null;
3012    }
3013
3014    @Override
3015    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3016        if (!sUserManager.exists(userId)) return null;
3017        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3018        synchronized (mPackages) {
3019            PackageParser.Provider p = mProviders.mProviders.get(component);
3020            if (DEBUG_PACKAGE_INFO) Log.v(
3021                TAG, "getProviderInfo " + component + ": " + p);
3022            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3023                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3024                if (ps == null) return null;
3025                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3026                        userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public String[] getSystemSharedLibraryNames() {
3034        Set<String> libSet;
3035        synchronized (mPackages) {
3036            libSet = mSharedLibraries.keySet();
3037            int size = libSet.size();
3038            if (size > 0) {
3039                String[] libs = new String[size];
3040                libSet.toArray(libs);
3041                return libs;
3042            }
3043        }
3044        return null;
3045    }
3046
3047    /**
3048     * @hide
3049     */
3050    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3051        synchronized (mPackages) {
3052            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3053            if (lib != null && lib.apk != null) {
3054                return mPackages.get(lib.apk);
3055            }
3056        }
3057        return null;
3058    }
3059
3060    @Override
3061    public FeatureInfo[] getSystemAvailableFeatures() {
3062        Collection<FeatureInfo> featSet;
3063        synchronized (mPackages) {
3064            featSet = mAvailableFeatures.values();
3065            int size = featSet.size();
3066            if (size > 0) {
3067                FeatureInfo[] features = new FeatureInfo[size+1];
3068                featSet.toArray(features);
3069                FeatureInfo fi = new FeatureInfo();
3070                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3071                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3072                features[size] = fi;
3073                return features;
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public boolean hasSystemFeature(String name) {
3081        synchronized (mPackages) {
3082            return mAvailableFeatures.containsKey(name);
3083        }
3084    }
3085
3086    private void checkValidCaller(int uid, int userId) {
3087        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3088            return;
3089
3090        throw new SecurityException("Caller uid=" + uid
3091                + " is not privileged to communicate with user=" + userId);
3092    }
3093
3094    @Override
3095    public int checkPermission(String permName, String pkgName, int userId) {
3096        if (!sUserManager.exists(userId)) {
3097            return PackageManager.PERMISSION_DENIED;
3098        }
3099
3100        synchronized (mPackages) {
3101            final PackageParser.Package p = mPackages.get(pkgName);
3102            if (p != null && p.mExtras != null) {
3103                final PackageSetting ps = (PackageSetting) p.mExtras;
3104                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3105                    return PackageManager.PERMISSION_GRANTED;
3106                }
3107            }
3108        }
3109
3110        return PackageManager.PERMISSION_DENIED;
3111    }
3112
3113    @Override
3114    public int checkUidPermission(String permName, int uid) {
3115        final int userId = UserHandle.getUserId(uid);
3116
3117        if (!sUserManager.exists(userId)) {
3118            return PackageManager.PERMISSION_DENIED;
3119        }
3120
3121        synchronized (mPackages) {
3122            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3123            if (obj != null) {
3124                final SettingBase ps = (SettingBase) obj;
3125                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3126                    return PackageManager.PERMISSION_GRANTED;
3127                }
3128            } else {
3129                ArraySet<String> perms = mSystemPermissions.get(uid);
3130                if (perms != null && perms.contains(permName)) {
3131                    return PackageManager.PERMISSION_GRANTED;
3132                }
3133            }
3134        }
3135
3136        return PackageManager.PERMISSION_DENIED;
3137    }
3138
3139    @Override
3140    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3141        if (UserHandle.getCallingUserId() != userId) {
3142            mContext.enforceCallingPermission(
3143                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3144                    "isPermissionRevokedByPolicy for user " + userId);
3145        }
3146
3147        if (checkPermission(permission, packageName, userId)
3148                == PackageManager.PERMISSION_GRANTED) {
3149            return false;
3150        }
3151
3152        final long identity = Binder.clearCallingIdentity();
3153        try {
3154            final int flags = getPermissionFlags(permission, packageName, userId);
3155            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3156        } finally {
3157            Binder.restoreCallingIdentity(identity);
3158        }
3159    }
3160
3161    /**
3162     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3163     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3164     * @param checkShell TODO(yamasani):
3165     * @param message the message to log on security exception
3166     */
3167    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3168            boolean checkShell, String message) {
3169        if (userId < 0) {
3170            throw new IllegalArgumentException("Invalid userId " + userId);
3171        }
3172        if (checkShell) {
3173            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3174        }
3175        if (userId == UserHandle.getUserId(callingUid)) return;
3176        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3177            if (requireFullPermission) {
3178                mContext.enforceCallingOrSelfPermission(
3179                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3180            } else {
3181                try {
3182                    mContext.enforceCallingOrSelfPermission(
3183                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3184                } catch (SecurityException se) {
3185                    mContext.enforceCallingOrSelfPermission(
3186                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3187                }
3188            }
3189        }
3190    }
3191
3192    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3193        if (callingUid == Process.SHELL_UID) {
3194            if (userHandle >= 0
3195                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3196                throw new SecurityException("Shell does not have permission to access user "
3197                        + userHandle);
3198            } else if (userHandle < 0) {
3199                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3200                        + Debug.getCallers(3));
3201            }
3202        }
3203    }
3204
3205    private BasePermission findPermissionTreeLP(String permName) {
3206        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3207            if (permName.startsWith(bp.name) &&
3208                    permName.length() > bp.name.length() &&
3209                    permName.charAt(bp.name.length()) == '.') {
3210                return bp;
3211            }
3212        }
3213        return null;
3214    }
3215
3216    private BasePermission checkPermissionTreeLP(String permName) {
3217        if (permName != null) {
3218            BasePermission bp = findPermissionTreeLP(permName);
3219            if (bp != null) {
3220                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3221                    return bp;
3222                }
3223                throw new SecurityException("Calling uid "
3224                        + Binder.getCallingUid()
3225                        + " is not allowed to add to permission tree "
3226                        + bp.name + " owned by uid " + bp.uid);
3227            }
3228        }
3229        throw new SecurityException("No permission tree found for " + permName);
3230    }
3231
3232    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3233        if (s1 == null) {
3234            return s2 == null;
3235        }
3236        if (s2 == null) {
3237            return false;
3238        }
3239        if (s1.getClass() != s2.getClass()) {
3240            return false;
3241        }
3242        return s1.equals(s2);
3243    }
3244
3245    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3246        if (pi1.icon != pi2.icon) return false;
3247        if (pi1.logo != pi2.logo) return false;
3248        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3249        if (!compareStrings(pi1.name, pi2.name)) return false;
3250        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3251        // We'll take care of setting this one.
3252        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3253        // These are not currently stored in settings.
3254        //if (!compareStrings(pi1.group, pi2.group)) return false;
3255        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3256        //if (pi1.labelRes != pi2.labelRes) return false;
3257        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3258        return true;
3259    }
3260
3261    int permissionInfoFootprint(PermissionInfo info) {
3262        int size = info.name.length();
3263        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3264        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3265        return size;
3266    }
3267
3268    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3269        int size = 0;
3270        for (BasePermission perm : mSettings.mPermissions.values()) {
3271            if (perm.uid == tree.uid) {
3272                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3273            }
3274        }
3275        return size;
3276    }
3277
3278    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3279        // We calculate the max size of permissions defined by this uid and throw
3280        // if that plus the size of 'info' would exceed our stated maximum.
3281        if (tree.uid != Process.SYSTEM_UID) {
3282            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3283            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3284                throw new SecurityException("Permission tree size cap exceeded");
3285            }
3286        }
3287    }
3288
3289    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3290        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3291            throw new SecurityException("Label must be specified in permission");
3292        }
3293        BasePermission tree = checkPermissionTreeLP(info.name);
3294        BasePermission bp = mSettings.mPermissions.get(info.name);
3295        boolean added = bp == null;
3296        boolean changed = true;
3297        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3298        if (added) {
3299            enforcePermissionCapLocked(info, tree);
3300            bp = new BasePermission(info.name, tree.sourcePackage,
3301                    BasePermission.TYPE_DYNAMIC);
3302        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3303            throw new SecurityException(
3304                    "Not allowed to modify non-dynamic permission "
3305                    + info.name);
3306        } else {
3307            if (bp.protectionLevel == fixedLevel
3308                    && bp.perm.owner.equals(tree.perm.owner)
3309                    && bp.uid == tree.uid
3310                    && comparePermissionInfos(bp.perm.info, info)) {
3311                changed = false;
3312            }
3313        }
3314        bp.protectionLevel = fixedLevel;
3315        info = new PermissionInfo(info);
3316        info.protectionLevel = fixedLevel;
3317        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3318        bp.perm.info.packageName = tree.perm.info.packageName;
3319        bp.uid = tree.uid;
3320        if (added) {
3321            mSettings.mPermissions.put(info.name, bp);
3322        }
3323        if (changed) {
3324            if (!async) {
3325                mSettings.writeLPr();
3326            } else {
3327                scheduleWriteSettingsLocked();
3328            }
3329        }
3330        return added;
3331    }
3332
3333    @Override
3334    public boolean addPermission(PermissionInfo info) {
3335        synchronized (mPackages) {
3336            return addPermissionLocked(info, false);
3337        }
3338    }
3339
3340    @Override
3341    public boolean addPermissionAsync(PermissionInfo info) {
3342        synchronized (mPackages) {
3343            return addPermissionLocked(info, true);
3344        }
3345    }
3346
3347    @Override
3348    public void removePermission(String name) {
3349        synchronized (mPackages) {
3350            checkPermissionTreeLP(name);
3351            BasePermission bp = mSettings.mPermissions.get(name);
3352            if (bp != null) {
3353                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3354                    throw new SecurityException(
3355                            "Not allowed to modify non-dynamic permission "
3356                            + name);
3357                }
3358                mSettings.mPermissions.remove(name);
3359                mSettings.writeLPr();
3360            }
3361        }
3362    }
3363
3364    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3365            BasePermission bp) {
3366        int index = pkg.requestedPermissions.indexOf(bp.name);
3367        if (index == -1) {
3368            throw new SecurityException("Package " + pkg.packageName
3369                    + " has not requested permission " + bp.name);
3370        }
3371        if (!bp.isRuntime()) {
3372            throw new SecurityException("Permission " + bp.name
3373                    + " is not a changeable permission type");
3374        }
3375    }
3376
3377    @Override
3378    public void grantRuntimePermission(String packageName, String name, final int userId) {
3379        if (!sUserManager.exists(userId)) {
3380            Log.e(TAG, "No such user:" + userId);
3381            return;
3382        }
3383
3384        mContext.enforceCallingOrSelfPermission(
3385                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3386                "grantRuntimePermission");
3387
3388        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3389                "grantRuntimePermission");
3390
3391        final int uid;
3392        final SettingBase sb;
3393
3394        synchronized (mPackages) {
3395            final PackageParser.Package pkg = mPackages.get(packageName);
3396            if (pkg == null) {
3397                throw new IllegalArgumentException("Unknown package: " + packageName);
3398            }
3399
3400            final BasePermission bp = mSettings.mPermissions.get(name);
3401            if (bp == null) {
3402                throw new IllegalArgumentException("Unknown permission: " + name);
3403            }
3404
3405            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3406
3407            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3408            sb = (SettingBase) pkg.mExtras;
3409            if (sb == null) {
3410                throw new IllegalArgumentException("Unknown package: " + packageName);
3411            }
3412
3413            final PermissionsState permissionsState = sb.getPermissionsState();
3414
3415            final int flags = permissionsState.getPermissionFlags(name, userId);
3416            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3417                throw new SecurityException("Cannot grant system fixed permission: "
3418                        + name + " for package: " + packageName);
3419            }
3420
3421            final int result = permissionsState.grantRuntimePermission(bp, userId);
3422            switch (result) {
3423                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3424                    return;
3425                }
3426
3427                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3428                    mHandler.post(new Runnable() {
3429                        @Override
3430                        public void run() {
3431                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3432                        }
3433                    });
3434                } break;
3435            }
3436
3437            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3438
3439            // Not critical if that is lost - app has to request again.
3440            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3441        }
3442
3443        // Only need to do this if user is initialized. Otherwise it's a new user
3444        // and there are no processes running as the user yet and there's no need
3445        // to make an expensive call to remount processes for the changed permissions.
3446        if (READ_EXTERNAL_STORAGE.equals(name)
3447                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3448            final long token = Binder.clearCallingIdentity();
3449            try {
3450                if (sUserManager.isInitialized(userId)) {
3451                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3452                            MountServiceInternal.class);
3453                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3454                }
3455            } finally {
3456                Binder.restoreCallingIdentity(token);
3457            }
3458        }
3459    }
3460
3461    @Override
3462    public void revokeRuntimePermission(String packageName, String name, int userId) {
3463        if (!sUserManager.exists(userId)) {
3464            Log.e(TAG, "No such user:" + userId);
3465            return;
3466        }
3467
3468        mContext.enforceCallingOrSelfPermission(
3469                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3470                "revokeRuntimePermission");
3471
3472        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3473                "revokeRuntimePermission");
3474
3475        final SettingBase sb;
3476
3477        synchronized (mPackages) {
3478            final PackageParser.Package pkg = mPackages.get(packageName);
3479            if (pkg == null) {
3480                throw new IllegalArgumentException("Unknown package: " + packageName);
3481            }
3482
3483            final BasePermission bp = mSettings.mPermissions.get(name);
3484            if (bp == null) {
3485                throw new IllegalArgumentException("Unknown permission: " + name);
3486            }
3487
3488            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3489
3490            sb = (SettingBase) pkg.mExtras;
3491            if (sb == null) {
3492                throw new IllegalArgumentException("Unknown package: " + packageName);
3493            }
3494
3495            final PermissionsState permissionsState = sb.getPermissionsState();
3496
3497            final int flags = permissionsState.getPermissionFlags(name, userId);
3498            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3499                throw new SecurityException("Cannot revoke system fixed permission: "
3500                        + name + " for package: " + packageName);
3501            }
3502
3503            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3504                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3505                return;
3506            }
3507
3508            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3509
3510            // Critical, after this call app should never have the permission.
3511            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3512        }
3513
3514        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3515    }
3516
3517    @Override
3518    public void resetRuntimePermissions() {
3519        mContext.enforceCallingOrSelfPermission(
3520                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3521                "revokeRuntimePermission");
3522
3523        int callingUid = Binder.getCallingUid();
3524        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3525            mContext.enforceCallingOrSelfPermission(
3526                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3527                    "resetRuntimePermissions");
3528        }
3529
3530        final int[] userIds;
3531
3532        synchronized (mPackages) {
3533            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3534            final int userCount = UserManagerService.getInstance().getUserIds().length;
3535            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3536        }
3537
3538        for (int userId : userIds) {
3539            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3540        }
3541    }
3542
3543    @Override
3544    public int getPermissionFlags(String name, String packageName, int userId) {
3545        if (!sUserManager.exists(userId)) {
3546            return 0;
3547        }
3548
3549        mContext.enforceCallingOrSelfPermission(
3550                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3551                "getPermissionFlags");
3552
3553        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3554                "getPermissionFlags");
3555
3556        synchronized (mPackages) {
3557            final PackageParser.Package pkg = mPackages.get(packageName);
3558            if (pkg == null) {
3559                throw new IllegalArgumentException("Unknown package: " + packageName);
3560            }
3561
3562            final BasePermission bp = mSettings.mPermissions.get(name);
3563            if (bp == null) {
3564                throw new IllegalArgumentException("Unknown permission: " + name);
3565            }
3566
3567            SettingBase sb = (SettingBase) pkg.mExtras;
3568            if (sb == null) {
3569                throw new IllegalArgumentException("Unknown package: " + packageName);
3570            }
3571
3572            PermissionsState permissionsState = sb.getPermissionsState();
3573            return permissionsState.getPermissionFlags(name, userId);
3574        }
3575    }
3576
3577    @Override
3578    public void updatePermissionFlags(String name, String packageName, int flagMask,
3579            int flagValues, int userId) {
3580        if (!sUserManager.exists(userId)) {
3581            return;
3582        }
3583
3584        mContext.enforceCallingOrSelfPermission(
3585                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3586                "updatePermissionFlags");
3587
3588        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3589                "updatePermissionFlags");
3590
3591        // Only the system can change system fixed flags.
3592        if (getCallingUid() != Process.SYSTEM_UID) {
3593            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3594            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3595        }
3596
3597        synchronized (mPackages) {
3598            final PackageParser.Package pkg = mPackages.get(packageName);
3599            if (pkg == null) {
3600                throw new IllegalArgumentException("Unknown package: " + packageName);
3601            }
3602
3603            final BasePermission bp = mSettings.mPermissions.get(name);
3604            if (bp == null) {
3605                throw new IllegalArgumentException("Unknown permission: " + name);
3606            }
3607
3608            SettingBase sb = (SettingBase) pkg.mExtras;
3609            if (sb == null) {
3610                throw new IllegalArgumentException("Unknown package: " + packageName);
3611            }
3612
3613            PermissionsState permissionsState = sb.getPermissionsState();
3614
3615            // Only the package manager can change flags for system component permissions.
3616            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3617            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3618                return;
3619            }
3620
3621            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3622
3623            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3624                // Install and runtime permissions are stored in different places,
3625                // so figure out what permission changed and persist the change.
3626                if (permissionsState.getInstallPermissionState(name) != null) {
3627                    scheduleWriteSettingsLocked();
3628                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3629                        || hadState) {
3630                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3631                }
3632            }
3633        }
3634    }
3635
3636    /**
3637     * Update the permission flags for all packages and runtime permissions of a user in order
3638     * to allow device or profile owner to remove POLICY_FIXED.
3639     */
3640    @Override
3641    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3642        if (!sUserManager.exists(userId)) {
3643            return;
3644        }
3645
3646        mContext.enforceCallingOrSelfPermission(
3647                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3648                "updatePermissionFlagsForAllApps");
3649
3650        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3651                "updatePermissionFlagsForAllApps");
3652
3653        // Only the system can change system fixed flags.
3654        if (getCallingUid() != Process.SYSTEM_UID) {
3655            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3656            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3657        }
3658
3659        synchronized (mPackages) {
3660            boolean changed = false;
3661            final int packageCount = mPackages.size();
3662            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3663                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3664                SettingBase sb = (SettingBase) pkg.mExtras;
3665                if (sb == null) {
3666                    continue;
3667                }
3668                PermissionsState permissionsState = sb.getPermissionsState();
3669                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3670                        userId, flagMask, flagValues);
3671            }
3672            if (changed) {
3673                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3674            }
3675        }
3676    }
3677
3678    @Override
3679    public boolean shouldShowRequestPermissionRationale(String permissionName,
3680            String packageName, int userId) {
3681        if (UserHandle.getCallingUserId() != userId) {
3682            mContext.enforceCallingPermission(
3683                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3684                    "canShowRequestPermissionRationale for user " + userId);
3685        }
3686
3687        final int uid = getPackageUid(packageName, userId);
3688        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3689            return false;
3690        }
3691
3692        if (checkPermission(permissionName, packageName, userId)
3693                == PackageManager.PERMISSION_GRANTED) {
3694            return false;
3695        }
3696
3697        final int flags;
3698
3699        final long identity = Binder.clearCallingIdentity();
3700        try {
3701            flags = getPermissionFlags(permissionName,
3702                    packageName, userId);
3703        } finally {
3704            Binder.restoreCallingIdentity(identity);
3705        }
3706
3707        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3708                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3709                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3710
3711        if ((flags & fixedFlags) != 0) {
3712            return false;
3713        }
3714
3715        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3716    }
3717
3718    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3719        BasePermission bp = mSettings.mPermissions.get(permission);
3720        if (bp == null) {
3721            throw new SecurityException("Missing " + permission + " permission");
3722        }
3723
3724        SettingBase sb = (SettingBase) pkg.mExtras;
3725        PermissionsState permissionsState = sb.getPermissionsState();
3726
3727        if (permissionsState.grantInstallPermission(bp) !=
3728                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3729            scheduleWriteSettingsLocked();
3730        }
3731    }
3732
3733    @Override
3734    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3735        mContext.enforceCallingOrSelfPermission(
3736                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3737                "addOnPermissionsChangeListener");
3738
3739        synchronized (mPackages) {
3740            mOnPermissionChangeListeners.addListenerLocked(listener);
3741        }
3742    }
3743
3744    @Override
3745    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3746        synchronized (mPackages) {
3747            mOnPermissionChangeListeners.removeListenerLocked(listener);
3748        }
3749    }
3750
3751    @Override
3752    public boolean isProtectedBroadcast(String actionName) {
3753        synchronized (mPackages) {
3754            return mProtectedBroadcasts.contains(actionName);
3755        }
3756    }
3757
3758    @Override
3759    public int checkSignatures(String pkg1, String pkg2) {
3760        synchronized (mPackages) {
3761            final PackageParser.Package p1 = mPackages.get(pkg1);
3762            final PackageParser.Package p2 = mPackages.get(pkg2);
3763            if (p1 == null || p1.mExtras == null
3764                    || p2 == null || p2.mExtras == null) {
3765                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3766            }
3767            return compareSignatures(p1.mSignatures, p2.mSignatures);
3768        }
3769    }
3770
3771    @Override
3772    public int checkUidSignatures(int uid1, int uid2) {
3773        // Map to base uids.
3774        uid1 = UserHandle.getAppId(uid1);
3775        uid2 = UserHandle.getAppId(uid2);
3776        // reader
3777        synchronized (mPackages) {
3778            Signature[] s1;
3779            Signature[] s2;
3780            Object obj = mSettings.getUserIdLPr(uid1);
3781            if (obj != null) {
3782                if (obj instanceof SharedUserSetting) {
3783                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3784                } else if (obj instanceof PackageSetting) {
3785                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3786                } else {
3787                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3788                }
3789            } else {
3790                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3791            }
3792            obj = mSettings.getUserIdLPr(uid2);
3793            if (obj != null) {
3794                if (obj instanceof SharedUserSetting) {
3795                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3796                } else if (obj instanceof PackageSetting) {
3797                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3798                } else {
3799                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3800                }
3801            } else {
3802                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3803            }
3804            return compareSignatures(s1, s2);
3805        }
3806    }
3807
3808    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3809        final long identity = Binder.clearCallingIdentity();
3810        try {
3811            if (sb instanceof SharedUserSetting) {
3812                SharedUserSetting sus = (SharedUserSetting) sb;
3813                final int packageCount = sus.packages.size();
3814                for (int i = 0; i < packageCount; i++) {
3815                    PackageSetting susPs = sus.packages.valueAt(i);
3816                    if (userId == UserHandle.USER_ALL) {
3817                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3818                    } else {
3819                        final int uid = UserHandle.getUid(userId, susPs.appId);
3820                        killUid(uid, reason);
3821                    }
3822                }
3823            } else if (sb instanceof PackageSetting) {
3824                PackageSetting ps = (PackageSetting) sb;
3825                if (userId == UserHandle.USER_ALL) {
3826                    killApplication(ps.pkg.packageName, ps.appId, reason);
3827                } else {
3828                    final int uid = UserHandle.getUid(userId, ps.appId);
3829                    killUid(uid, reason);
3830                }
3831            }
3832        } finally {
3833            Binder.restoreCallingIdentity(identity);
3834        }
3835    }
3836
3837    private static void killUid(int uid, String reason) {
3838        IActivityManager am = ActivityManagerNative.getDefault();
3839        if (am != null) {
3840            try {
3841                am.killUid(uid, reason);
3842            } catch (RemoteException e) {
3843                /* ignore - same process */
3844            }
3845        }
3846    }
3847
3848    /**
3849     * Compares two sets of signatures. Returns:
3850     * <br />
3851     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3852     * <br />
3853     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3854     * <br />
3855     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3856     * <br />
3857     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3858     * <br />
3859     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3860     */
3861    static int compareSignatures(Signature[] s1, Signature[] s2) {
3862        if (s1 == null) {
3863            return s2 == null
3864                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3865                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3866        }
3867
3868        if (s2 == null) {
3869            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3870        }
3871
3872        if (s1.length != s2.length) {
3873            return PackageManager.SIGNATURE_NO_MATCH;
3874        }
3875
3876        // Since both signature sets are of size 1, we can compare without HashSets.
3877        if (s1.length == 1) {
3878            return s1[0].equals(s2[0]) ?
3879                    PackageManager.SIGNATURE_MATCH :
3880                    PackageManager.SIGNATURE_NO_MATCH;
3881        }
3882
3883        ArraySet<Signature> set1 = new ArraySet<Signature>();
3884        for (Signature sig : s1) {
3885            set1.add(sig);
3886        }
3887        ArraySet<Signature> set2 = new ArraySet<Signature>();
3888        for (Signature sig : s2) {
3889            set2.add(sig);
3890        }
3891        // Make sure s2 contains all signatures in s1.
3892        if (set1.equals(set2)) {
3893            return PackageManager.SIGNATURE_MATCH;
3894        }
3895        return PackageManager.SIGNATURE_NO_MATCH;
3896    }
3897
3898    /**
3899     * If the database version for this type of package (internal storage or
3900     * external storage) is less than the version where package signatures
3901     * were updated, return true.
3902     */
3903    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3904        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3905                DatabaseVersion.SIGNATURE_END_ENTITY))
3906                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3907                        DatabaseVersion.SIGNATURE_END_ENTITY));
3908    }
3909
3910    /**
3911     * Used for backward compatibility to make sure any packages with
3912     * certificate chains get upgraded to the new style. {@code existingSigs}
3913     * will be in the old format (since they were stored on disk from before the
3914     * system upgrade) and {@code scannedSigs} will be in the newer format.
3915     */
3916    private int compareSignaturesCompat(PackageSignatures existingSigs,
3917            PackageParser.Package scannedPkg) {
3918        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3919            return PackageManager.SIGNATURE_NO_MATCH;
3920        }
3921
3922        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3923        for (Signature sig : existingSigs.mSignatures) {
3924            existingSet.add(sig);
3925        }
3926        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3927        for (Signature sig : scannedPkg.mSignatures) {
3928            try {
3929                Signature[] chainSignatures = sig.getChainSignatures();
3930                for (Signature chainSig : chainSignatures) {
3931                    scannedCompatSet.add(chainSig);
3932                }
3933            } catch (CertificateEncodingException e) {
3934                scannedCompatSet.add(sig);
3935            }
3936        }
3937        /*
3938         * Make sure the expanded scanned set contains all signatures in the
3939         * existing one.
3940         */
3941        if (scannedCompatSet.equals(existingSet)) {
3942            // Migrate the old signatures to the new scheme.
3943            existingSigs.assignSignatures(scannedPkg.mSignatures);
3944            // The new KeySets will be re-added later in the scanning process.
3945            synchronized (mPackages) {
3946                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3947            }
3948            return PackageManager.SIGNATURE_MATCH;
3949        }
3950        return PackageManager.SIGNATURE_NO_MATCH;
3951    }
3952
3953    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3954        if (isExternal(scannedPkg)) {
3955            return mSettings.isExternalDatabaseVersionOlderThan(
3956                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3957        } else {
3958            return mSettings.isInternalDatabaseVersionOlderThan(
3959                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3960        }
3961    }
3962
3963    private int compareSignaturesRecover(PackageSignatures existingSigs,
3964            PackageParser.Package scannedPkg) {
3965        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3966            return PackageManager.SIGNATURE_NO_MATCH;
3967        }
3968
3969        String msg = null;
3970        try {
3971            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3972                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3973                        + scannedPkg.packageName);
3974                return PackageManager.SIGNATURE_MATCH;
3975            }
3976        } catch (CertificateException e) {
3977            msg = e.getMessage();
3978        }
3979
3980        logCriticalInfo(Log.INFO,
3981                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3982        return PackageManager.SIGNATURE_NO_MATCH;
3983    }
3984
3985    @Override
3986    public String[] getPackagesForUid(int uid) {
3987        uid = UserHandle.getAppId(uid);
3988        // reader
3989        synchronized (mPackages) {
3990            Object obj = mSettings.getUserIdLPr(uid);
3991            if (obj instanceof SharedUserSetting) {
3992                final SharedUserSetting sus = (SharedUserSetting) obj;
3993                final int N = sus.packages.size();
3994                final String[] res = new String[N];
3995                final Iterator<PackageSetting> it = sus.packages.iterator();
3996                int i = 0;
3997                while (it.hasNext()) {
3998                    res[i++] = it.next().name;
3999                }
4000                return res;
4001            } else if (obj instanceof PackageSetting) {
4002                final PackageSetting ps = (PackageSetting) obj;
4003                return new String[] { ps.name };
4004            }
4005        }
4006        return null;
4007    }
4008
4009    @Override
4010    public String getNameForUid(int uid) {
4011        // reader
4012        synchronized (mPackages) {
4013            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4014            if (obj instanceof SharedUserSetting) {
4015                final SharedUserSetting sus = (SharedUserSetting) obj;
4016                return sus.name + ":" + sus.userId;
4017            } else if (obj instanceof PackageSetting) {
4018                final PackageSetting ps = (PackageSetting) obj;
4019                return ps.name;
4020            }
4021        }
4022        return null;
4023    }
4024
4025    @Override
4026    public int getUidForSharedUser(String sharedUserName) {
4027        if(sharedUserName == null) {
4028            return -1;
4029        }
4030        // reader
4031        synchronized (mPackages) {
4032            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4033            if (suid == null) {
4034                return -1;
4035            }
4036            return suid.userId;
4037        }
4038    }
4039
4040    @Override
4041    public int getFlagsForUid(int uid) {
4042        synchronized (mPackages) {
4043            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4044            if (obj instanceof SharedUserSetting) {
4045                final SharedUserSetting sus = (SharedUserSetting) obj;
4046                return sus.pkgFlags;
4047            } else if (obj instanceof PackageSetting) {
4048                final PackageSetting ps = (PackageSetting) obj;
4049                return ps.pkgFlags;
4050            }
4051        }
4052        return 0;
4053    }
4054
4055    @Override
4056    public int getPrivateFlagsForUid(int uid) {
4057        synchronized (mPackages) {
4058            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4059            if (obj instanceof SharedUserSetting) {
4060                final SharedUserSetting sus = (SharedUserSetting) obj;
4061                return sus.pkgPrivateFlags;
4062            } else if (obj instanceof PackageSetting) {
4063                final PackageSetting ps = (PackageSetting) obj;
4064                return ps.pkgPrivateFlags;
4065            }
4066        }
4067        return 0;
4068    }
4069
4070    @Override
4071    public boolean isUidPrivileged(int uid) {
4072        uid = UserHandle.getAppId(uid);
4073        // reader
4074        synchronized (mPackages) {
4075            Object obj = mSettings.getUserIdLPr(uid);
4076            if (obj instanceof SharedUserSetting) {
4077                final SharedUserSetting sus = (SharedUserSetting) obj;
4078                final Iterator<PackageSetting> it = sus.packages.iterator();
4079                while (it.hasNext()) {
4080                    if (it.next().isPrivileged()) {
4081                        return true;
4082                    }
4083                }
4084            } else if (obj instanceof PackageSetting) {
4085                final PackageSetting ps = (PackageSetting) obj;
4086                return ps.isPrivileged();
4087            }
4088        }
4089        return false;
4090    }
4091
4092    @Override
4093    public String[] getAppOpPermissionPackages(String permissionName) {
4094        synchronized (mPackages) {
4095            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4096            if (pkgs == null) {
4097                return null;
4098            }
4099            return pkgs.toArray(new String[pkgs.size()]);
4100        }
4101    }
4102
4103    @Override
4104    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4105            int flags, int userId) {
4106        if (!sUserManager.exists(userId)) return null;
4107        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4108        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4109        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4110    }
4111
4112    @Override
4113    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4114            IntentFilter filter, int match, ComponentName activity) {
4115        final int userId = UserHandle.getCallingUserId();
4116        if (DEBUG_PREFERRED) {
4117            Log.v(TAG, "setLastChosenActivity intent=" + intent
4118                + " resolvedType=" + resolvedType
4119                + " flags=" + flags
4120                + " filter=" + filter
4121                + " match=" + match
4122                + " activity=" + activity);
4123            filter.dump(new PrintStreamPrinter(System.out), "    ");
4124        }
4125        intent.setComponent(null);
4126        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4127        // Find any earlier preferred or last chosen entries and nuke them
4128        findPreferredActivity(intent, resolvedType,
4129                flags, query, 0, false, true, false, userId);
4130        // Add the new activity as the last chosen for this filter
4131        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4132                "Setting last chosen");
4133    }
4134
4135    @Override
4136    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4137        final int userId = UserHandle.getCallingUserId();
4138        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4139        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4140        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4141                false, false, false, userId);
4142    }
4143
4144    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4145            int flags, List<ResolveInfo> query, int userId) {
4146        if (query != null) {
4147            final int N = query.size();
4148            if (N == 1) {
4149                return query.get(0);
4150            } else if (N > 1) {
4151                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4152                // If there is more than one activity with the same priority,
4153                // then let the user decide between them.
4154                ResolveInfo r0 = query.get(0);
4155                ResolveInfo r1 = query.get(1);
4156                if (DEBUG_INTENT_MATCHING || debug) {
4157                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4158                            + r1.activityInfo.name + "=" + r1.priority);
4159                }
4160                // If the first activity has a higher priority, or a different
4161                // default, then it is always desireable to pick it.
4162                if (r0.priority != r1.priority
4163                        || r0.preferredOrder != r1.preferredOrder
4164                        || r0.isDefault != r1.isDefault) {
4165                    return query.get(0);
4166                }
4167                // If we have saved a preference for a preferred activity for
4168                // this Intent, use that.
4169                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4170                        flags, query, r0.priority, true, false, debug, userId);
4171                if (ri != null) {
4172                    return ri;
4173                }
4174                if (userId != 0) {
4175                    ri = new ResolveInfo(mResolveInfo);
4176                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4177                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4178                            ri.activityInfo.applicationInfo);
4179                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4180                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4181                    return ri;
4182                }
4183                return mResolveInfo;
4184            }
4185        }
4186        return null;
4187    }
4188
4189    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4190            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4191        final int N = query.size();
4192        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4193                .get(userId);
4194        // Get the list of persistent preferred activities that handle the intent
4195        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4196        List<PersistentPreferredActivity> pprefs = ppir != null
4197                ? ppir.queryIntent(intent, resolvedType,
4198                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4199                : null;
4200        if (pprefs != null && pprefs.size() > 0) {
4201            final int M = pprefs.size();
4202            for (int i=0; i<M; i++) {
4203                final PersistentPreferredActivity ppa = pprefs.get(i);
4204                if (DEBUG_PREFERRED || debug) {
4205                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4206                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4207                            + "\n  component=" + ppa.mComponent);
4208                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4209                }
4210                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4211                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4212                if (DEBUG_PREFERRED || debug) {
4213                    Slog.v(TAG, "Found persistent preferred activity:");
4214                    if (ai != null) {
4215                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4216                    } else {
4217                        Slog.v(TAG, "  null");
4218                    }
4219                }
4220                if (ai == null) {
4221                    // This previously registered persistent preferred activity
4222                    // component is no longer known. Ignore it and do NOT remove it.
4223                    continue;
4224                }
4225                for (int j=0; j<N; j++) {
4226                    final ResolveInfo ri = query.get(j);
4227                    if (!ri.activityInfo.applicationInfo.packageName
4228                            .equals(ai.applicationInfo.packageName)) {
4229                        continue;
4230                    }
4231                    if (!ri.activityInfo.name.equals(ai.name)) {
4232                        continue;
4233                    }
4234                    //  Found a persistent preference that can handle the intent.
4235                    if (DEBUG_PREFERRED || debug) {
4236                        Slog.v(TAG, "Returning persistent preferred activity: " +
4237                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4238                    }
4239                    return ri;
4240                }
4241            }
4242        }
4243        return null;
4244    }
4245
4246    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4247            List<ResolveInfo> query, int priority, boolean always,
4248            boolean removeMatches, boolean debug, int userId) {
4249        if (!sUserManager.exists(userId)) return null;
4250        // writer
4251        synchronized (mPackages) {
4252            if (intent.getSelector() != null) {
4253                intent = intent.getSelector();
4254            }
4255            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4256
4257            // Try to find a matching persistent preferred activity.
4258            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4259                    debug, userId);
4260
4261            // If a persistent preferred activity matched, use it.
4262            if (pri != null) {
4263                return pri;
4264            }
4265
4266            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4267            // Get the list of preferred activities that handle the intent
4268            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4269            List<PreferredActivity> prefs = pir != null
4270                    ? pir.queryIntent(intent, resolvedType,
4271                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4272                    : null;
4273            if (prefs != null && prefs.size() > 0) {
4274                boolean changed = false;
4275                try {
4276                    // First figure out how good the original match set is.
4277                    // We will only allow preferred activities that came
4278                    // from the same match quality.
4279                    int match = 0;
4280
4281                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4282
4283                    final int N = query.size();
4284                    for (int j=0; j<N; j++) {
4285                        final ResolveInfo ri = query.get(j);
4286                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4287                                + ": 0x" + Integer.toHexString(match));
4288                        if (ri.match > match) {
4289                            match = ri.match;
4290                        }
4291                    }
4292
4293                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4294                            + Integer.toHexString(match));
4295
4296                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4297                    final int M = prefs.size();
4298                    for (int i=0; i<M; i++) {
4299                        final PreferredActivity pa = prefs.get(i);
4300                        if (DEBUG_PREFERRED || debug) {
4301                            Slog.v(TAG, "Checking PreferredActivity ds="
4302                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4303                                    + "\n  component=" + pa.mPref.mComponent);
4304                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4305                        }
4306                        if (pa.mPref.mMatch != match) {
4307                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4308                                    + Integer.toHexString(pa.mPref.mMatch));
4309                            continue;
4310                        }
4311                        // If it's not an "always" type preferred activity and that's what we're
4312                        // looking for, skip it.
4313                        if (always && !pa.mPref.mAlways) {
4314                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4315                            continue;
4316                        }
4317                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4318                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4319                        if (DEBUG_PREFERRED || debug) {
4320                            Slog.v(TAG, "Found preferred activity:");
4321                            if (ai != null) {
4322                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4323                            } else {
4324                                Slog.v(TAG, "  null");
4325                            }
4326                        }
4327                        if (ai == null) {
4328                            // This previously registered preferred activity
4329                            // component is no longer known.  Most likely an update
4330                            // to the app was installed and in the new version this
4331                            // component no longer exists.  Clean it up by removing
4332                            // it from the preferred activities list, and skip it.
4333                            Slog.w(TAG, "Removing dangling preferred activity: "
4334                                    + pa.mPref.mComponent);
4335                            pir.removeFilter(pa);
4336                            changed = true;
4337                            continue;
4338                        }
4339                        for (int j=0; j<N; j++) {
4340                            final ResolveInfo ri = query.get(j);
4341                            if (!ri.activityInfo.applicationInfo.packageName
4342                                    .equals(ai.applicationInfo.packageName)) {
4343                                continue;
4344                            }
4345                            if (!ri.activityInfo.name.equals(ai.name)) {
4346                                continue;
4347                            }
4348
4349                            if (removeMatches) {
4350                                pir.removeFilter(pa);
4351                                changed = true;
4352                                if (DEBUG_PREFERRED) {
4353                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4354                                }
4355                                break;
4356                            }
4357
4358                            // Okay we found a previously set preferred or last chosen app.
4359                            // If the result set is different from when this
4360                            // was created, we need to clear it and re-ask the
4361                            // user their preference, if we're looking for an "always" type entry.
4362                            if (always && !pa.mPref.sameSet(query)) {
4363                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4364                                        + intent + " type " + resolvedType);
4365                                if (DEBUG_PREFERRED) {
4366                                    Slog.v(TAG, "Removing preferred activity since set changed "
4367                                            + pa.mPref.mComponent);
4368                                }
4369                                pir.removeFilter(pa);
4370                                // Re-add the filter as a "last chosen" entry (!always)
4371                                PreferredActivity lastChosen = new PreferredActivity(
4372                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4373                                pir.addFilter(lastChosen);
4374                                changed = true;
4375                                return null;
4376                            }
4377
4378                            // Yay! Either the set matched or we're looking for the last chosen
4379                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4380                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4381                            return ri;
4382                        }
4383                    }
4384                } finally {
4385                    if (changed) {
4386                        if (DEBUG_PREFERRED) {
4387                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4388                        }
4389                        scheduleWritePackageRestrictionsLocked(userId);
4390                    }
4391                }
4392            }
4393        }
4394        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4395        return null;
4396    }
4397
4398    /*
4399     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4400     */
4401    @Override
4402    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4403            int targetUserId) {
4404        mContext.enforceCallingOrSelfPermission(
4405                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4406        List<CrossProfileIntentFilter> matches =
4407                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4408        if (matches != null) {
4409            int size = matches.size();
4410            for (int i = 0; i < size; i++) {
4411                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4412            }
4413        }
4414        if (hasWebURI(intent)) {
4415            // cross-profile app linking works only towards the parent.
4416            final UserInfo parent = getProfileParent(sourceUserId);
4417            synchronized(mPackages) {
4418                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4419                        intent, resolvedType, 0, sourceUserId, parent.id);
4420                return xpDomainInfo != null;
4421            }
4422        }
4423        return false;
4424    }
4425
4426    private UserInfo getProfileParent(int userId) {
4427        final long identity = Binder.clearCallingIdentity();
4428        try {
4429            return sUserManager.getProfileParent(userId);
4430        } finally {
4431            Binder.restoreCallingIdentity(identity);
4432        }
4433    }
4434
4435    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4436            String resolvedType, int userId) {
4437        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4438        if (resolver != null) {
4439            return resolver.queryIntent(intent, resolvedType, false, userId);
4440        }
4441        return null;
4442    }
4443
4444    @Override
4445    public List<ResolveInfo> queryIntentActivities(Intent intent,
4446            String resolvedType, int flags, int userId) {
4447        if (!sUserManager.exists(userId)) return Collections.emptyList();
4448        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4449        ComponentName comp = intent.getComponent();
4450        if (comp == null) {
4451            if (intent.getSelector() != null) {
4452                intent = intent.getSelector();
4453                comp = intent.getComponent();
4454            }
4455        }
4456
4457        if (comp != null) {
4458            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4459            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4460            if (ai != null) {
4461                final ResolveInfo ri = new ResolveInfo();
4462                ri.activityInfo = ai;
4463                list.add(ri);
4464            }
4465            return list;
4466        }
4467
4468        // reader
4469        synchronized (mPackages) {
4470            final String pkgName = intent.getPackage();
4471            if (pkgName == null) {
4472                List<CrossProfileIntentFilter> matchingFilters =
4473                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4474                // Check for results that need to skip the current profile.
4475                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4476                        resolvedType, flags, userId);
4477                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4478                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4479                    result.add(xpResolveInfo);
4480                    return filterIfNotPrimaryUser(result, userId);
4481                }
4482
4483                // Check for results in the current profile.
4484                List<ResolveInfo> result = mActivities.queryIntent(
4485                        intent, resolvedType, flags, userId);
4486
4487                // Check for cross profile results.
4488                xpResolveInfo = queryCrossProfileIntents(
4489                        matchingFilters, intent, resolvedType, flags, userId);
4490                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4491                    result.add(xpResolveInfo);
4492                    Collections.sort(result, mResolvePrioritySorter);
4493                }
4494                result = filterIfNotPrimaryUser(result, userId);
4495                if (hasWebURI(intent)) {
4496                    CrossProfileDomainInfo xpDomainInfo = null;
4497                    final UserInfo parent = getProfileParent(userId);
4498                    if (parent != null) {
4499                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4500                                flags, userId, parent.id);
4501                    }
4502                    if (xpDomainInfo != null) {
4503                        if (xpResolveInfo != null) {
4504                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4505                            // in the result.
4506                            result.remove(xpResolveInfo);
4507                        }
4508                        if (result.size() == 0) {
4509                            result.add(xpDomainInfo.resolveInfo);
4510                            return result;
4511                        }
4512                    } else if (result.size() <= 1) {
4513                        return result;
4514                    }
4515                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4516                            xpDomainInfo, userId);
4517                    Collections.sort(result, mResolvePrioritySorter);
4518                }
4519                return result;
4520            }
4521            final PackageParser.Package pkg = mPackages.get(pkgName);
4522            if (pkg != null) {
4523                return filterIfNotPrimaryUser(
4524                        mActivities.queryIntentForPackage(
4525                                intent, resolvedType, flags, pkg.activities, userId),
4526                        userId);
4527            }
4528            return new ArrayList<ResolveInfo>();
4529        }
4530    }
4531
4532    private static class CrossProfileDomainInfo {
4533        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4534        ResolveInfo resolveInfo;
4535        /* Best domain verification status of the activities found in the other profile */
4536        int bestDomainVerificationStatus;
4537    }
4538
4539    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4540            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4541        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4542                sourceUserId)) {
4543            return null;
4544        }
4545        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4546                resolvedType, flags, parentUserId);
4547
4548        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4549            return null;
4550        }
4551        CrossProfileDomainInfo result = null;
4552        int size = resultTargetUser.size();
4553        for (int i = 0; i < size; i++) {
4554            ResolveInfo riTargetUser = resultTargetUser.get(i);
4555            // Intent filter verification is only for filters that specify a host. So don't return
4556            // those that handle all web uris.
4557            if (riTargetUser.handleAllWebDataURI) {
4558                continue;
4559            }
4560            String packageName = riTargetUser.activityInfo.packageName;
4561            PackageSetting ps = mSettings.mPackages.get(packageName);
4562            if (ps == null) {
4563                continue;
4564            }
4565            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4566            int status = (int)(verificationState >> 32);
4567            if (result == null) {
4568                result = new CrossProfileDomainInfo();
4569                result.resolveInfo =
4570                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4571                result.bestDomainVerificationStatus = status;
4572            } else {
4573                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4574                        result.bestDomainVerificationStatus);
4575            }
4576        }
4577        // Don't consider matches with status NEVER across profiles.
4578        if (result != null && result.bestDomainVerificationStatus
4579                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4580            return null;
4581        }
4582        return result;
4583    }
4584
4585    /**
4586     * Verification statuses are ordered from the worse to the best, except for
4587     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4588     */
4589    private int bestDomainVerificationStatus(int status1, int status2) {
4590        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4591            return status2;
4592        }
4593        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4594            return status1;
4595        }
4596        return (int) MathUtils.max(status1, status2);
4597    }
4598
4599    private boolean isUserEnabled(int userId) {
4600        long callingId = Binder.clearCallingIdentity();
4601        try {
4602            UserInfo userInfo = sUserManager.getUserInfo(userId);
4603            return userInfo != null && userInfo.isEnabled();
4604        } finally {
4605            Binder.restoreCallingIdentity(callingId);
4606        }
4607    }
4608
4609    /**
4610     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4611     *
4612     * @return filtered list
4613     */
4614    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4615        if (userId == UserHandle.USER_OWNER) {
4616            return resolveInfos;
4617        }
4618        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4619            ResolveInfo info = resolveInfos.get(i);
4620            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4621                resolveInfos.remove(i);
4622            }
4623        }
4624        return resolveInfos;
4625    }
4626
4627    private static boolean hasWebURI(Intent intent) {
4628        if (intent.getData() == null) {
4629            return false;
4630        }
4631        final String scheme = intent.getScheme();
4632        if (TextUtils.isEmpty(scheme)) {
4633            return false;
4634        }
4635        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4636    }
4637
4638    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4639            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4640            int userId) {
4641        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4642
4643        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4644            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4645                    candidates.size());
4646        }
4647
4648        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4649        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4650        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4651        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4652        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4653
4654        synchronized (mPackages) {
4655            final int count = candidates.size();
4656            // First, try to use linked apps. Partition the candidates into four lists:
4657            // one for the final results, one for the "do not use ever", one for "undefined status"
4658            // and finally one for "browser app type".
4659            for (int n=0; n<count; n++) {
4660                ResolveInfo info = candidates.get(n);
4661                String packageName = info.activityInfo.packageName;
4662                PackageSetting ps = mSettings.mPackages.get(packageName);
4663                if (ps != null) {
4664                    // Add to the special match all list (Browser use case)
4665                    if (info.handleAllWebDataURI) {
4666                        matchAllList.add(info);
4667                        continue;
4668                    }
4669                    // Try to get the status from User settings first
4670                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4671                    int status = (int)(packedStatus >> 32);
4672                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4673                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4674                        if (DEBUG_DOMAIN_VERIFICATION) {
4675                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4676                                    + " : linkgen=" + linkGeneration);
4677                        }
4678                        // Use link-enabled generation as preferredOrder, i.e.
4679                        // prefer newly-enabled over earlier-enabled.
4680                        info.preferredOrder = linkGeneration;
4681                        alwaysList.add(info);
4682                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4683                        if (DEBUG_DOMAIN_VERIFICATION) {
4684                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4685                        }
4686                        neverList.add(info);
4687                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4688                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4689                        if (DEBUG_DOMAIN_VERIFICATION) {
4690                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4691                        }
4692                        undefinedList.add(info);
4693                    }
4694                }
4695            }
4696            // First try to add the "always" resolution(s) for the current user, if any
4697            if (alwaysList.size() > 0) {
4698                result.addAll(alwaysList);
4699            // if there is an "always" for the parent user, add it.
4700            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4701                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4702                result.add(xpDomainInfo.resolveInfo);
4703            } else {
4704                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4705                result.addAll(undefinedList);
4706                if (xpDomainInfo != null && (
4707                        xpDomainInfo.bestDomainVerificationStatus
4708                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4709                        || xpDomainInfo.bestDomainVerificationStatus
4710                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4711                    result.add(xpDomainInfo.resolveInfo);
4712                }
4713                // Also add Browsers (all of them or only the default one)
4714                if ((matchFlags & MATCH_ALL) != 0) {
4715                    result.addAll(matchAllList);
4716                } else {
4717                    // Browser/generic handling case.  If there's a default browser, go straight
4718                    // to that (but only if there is no other higher-priority match).
4719                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4720                    int maxMatchPrio = 0;
4721                    ResolveInfo defaultBrowserMatch = null;
4722                    final int numCandidates = matchAllList.size();
4723                    for (int n = 0; n < numCandidates; n++) {
4724                        ResolveInfo info = matchAllList.get(n);
4725                        // track the highest overall match priority...
4726                        if (info.priority > maxMatchPrio) {
4727                            maxMatchPrio = info.priority;
4728                        }
4729                        // ...and the highest-priority default browser match
4730                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4731                            if (defaultBrowserMatch == null
4732                                    || (defaultBrowserMatch.priority < info.priority)) {
4733                                if (debug) {
4734                                    Slog.v(TAG, "Considering default browser match " + info);
4735                                }
4736                                defaultBrowserMatch = info;
4737                            }
4738                        }
4739                    }
4740                    if (defaultBrowserMatch != null
4741                            && defaultBrowserMatch.priority >= maxMatchPrio
4742                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4743                    {
4744                        if (debug) {
4745                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4746                        }
4747                        result.add(defaultBrowserMatch);
4748                    } else {
4749                        result.addAll(matchAllList);
4750                    }
4751                }
4752
4753                // If there is nothing selected, add all candidates and remove the ones that the user
4754                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4755                if (result.size() == 0) {
4756                    result.addAll(candidates);
4757                    result.removeAll(neverList);
4758                }
4759            }
4760        }
4761        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4762            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4763                    result.size());
4764            for (ResolveInfo info : result) {
4765                Slog.v(TAG, "  + " + info.activityInfo);
4766            }
4767        }
4768        return result;
4769    }
4770
4771    // Returns a packed value as a long:
4772    //
4773    // high 'int'-sized word: link status: undefined/ask/never/always.
4774    // low 'int'-sized word: relative priority among 'always' results.
4775    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4776        long result = ps.getDomainVerificationStatusForUser(userId);
4777        // if none available, get the master status
4778        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4779            if (ps.getIntentFilterVerificationInfo() != null) {
4780                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4781            }
4782        }
4783        return result;
4784    }
4785
4786    private ResolveInfo querySkipCurrentProfileIntents(
4787            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4788            int flags, int sourceUserId) {
4789        if (matchingFilters != null) {
4790            int size = matchingFilters.size();
4791            for (int i = 0; i < size; i ++) {
4792                CrossProfileIntentFilter filter = matchingFilters.get(i);
4793                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4794                    // Checking if there are activities in the target user that can handle the
4795                    // intent.
4796                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4797                            flags, sourceUserId);
4798                    if (resolveInfo != null) {
4799                        return resolveInfo;
4800                    }
4801                }
4802            }
4803        }
4804        return null;
4805    }
4806
4807    // Return matching ResolveInfo if any for skip current profile intent filters.
4808    private ResolveInfo queryCrossProfileIntents(
4809            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4810            int flags, int sourceUserId) {
4811        if (matchingFilters != null) {
4812            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4813            // match the same intent. For performance reasons, it is better not to
4814            // run queryIntent twice for the same userId
4815            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4816            int size = matchingFilters.size();
4817            for (int i = 0; i < size; i++) {
4818                CrossProfileIntentFilter filter = matchingFilters.get(i);
4819                int targetUserId = filter.getTargetUserId();
4820                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4821                        && !alreadyTriedUserIds.get(targetUserId)) {
4822                    // Checking if there are activities in the target user that can handle the
4823                    // intent.
4824                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4825                            flags, sourceUserId);
4826                    if (resolveInfo != null) return resolveInfo;
4827                    alreadyTriedUserIds.put(targetUserId, true);
4828                }
4829            }
4830        }
4831        return null;
4832    }
4833
4834    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4835            String resolvedType, int flags, int sourceUserId) {
4836        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4837                resolvedType, flags, filter.getTargetUserId());
4838        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4839            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4840        }
4841        return null;
4842    }
4843
4844    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4845            int sourceUserId, int targetUserId) {
4846        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4847        String className;
4848        if (targetUserId == UserHandle.USER_OWNER) {
4849            className = FORWARD_INTENT_TO_USER_OWNER;
4850        } else {
4851            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4852        }
4853        ComponentName forwardingActivityComponentName = new ComponentName(
4854                mAndroidApplication.packageName, className);
4855        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4856                sourceUserId);
4857        if (targetUserId == UserHandle.USER_OWNER) {
4858            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4859            forwardingResolveInfo.noResourceId = true;
4860        }
4861        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4862        forwardingResolveInfo.priority = 0;
4863        forwardingResolveInfo.preferredOrder = 0;
4864        forwardingResolveInfo.match = 0;
4865        forwardingResolveInfo.isDefault = true;
4866        forwardingResolveInfo.filter = filter;
4867        forwardingResolveInfo.targetUserId = targetUserId;
4868        return forwardingResolveInfo;
4869    }
4870
4871    @Override
4872    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4873            Intent[] specifics, String[] specificTypes, Intent intent,
4874            String resolvedType, int flags, int userId) {
4875        if (!sUserManager.exists(userId)) return Collections.emptyList();
4876        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4877                false, "query intent activity options");
4878        final String resultsAction = intent.getAction();
4879
4880        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4881                | PackageManager.GET_RESOLVED_FILTER, userId);
4882
4883        if (DEBUG_INTENT_MATCHING) {
4884            Log.v(TAG, "Query " + intent + ": " + results);
4885        }
4886
4887        int specificsPos = 0;
4888        int N;
4889
4890        // todo: note that the algorithm used here is O(N^2).  This
4891        // isn't a problem in our current environment, but if we start running
4892        // into situations where we have more than 5 or 10 matches then this
4893        // should probably be changed to something smarter...
4894
4895        // First we go through and resolve each of the specific items
4896        // that were supplied, taking care of removing any corresponding
4897        // duplicate items in the generic resolve list.
4898        if (specifics != null) {
4899            for (int i=0; i<specifics.length; i++) {
4900                final Intent sintent = specifics[i];
4901                if (sintent == null) {
4902                    continue;
4903                }
4904
4905                if (DEBUG_INTENT_MATCHING) {
4906                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4907                }
4908
4909                String action = sintent.getAction();
4910                if (resultsAction != null && resultsAction.equals(action)) {
4911                    // If this action was explicitly requested, then don't
4912                    // remove things that have it.
4913                    action = null;
4914                }
4915
4916                ResolveInfo ri = null;
4917                ActivityInfo ai = null;
4918
4919                ComponentName comp = sintent.getComponent();
4920                if (comp == null) {
4921                    ri = resolveIntent(
4922                        sintent,
4923                        specificTypes != null ? specificTypes[i] : null,
4924                            flags, userId);
4925                    if (ri == null) {
4926                        continue;
4927                    }
4928                    if (ri == mResolveInfo) {
4929                        // ACK!  Must do something better with this.
4930                    }
4931                    ai = ri.activityInfo;
4932                    comp = new ComponentName(ai.applicationInfo.packageName,
4933                            ai.name);
4934                } else {
4935                    ai = getActivityInfo(comp, flags, userId);
4936                    if (ai == null) {
4937                        continue;
4938                    }
4939                }
4940
4941                // Look for any generic query activities that are duplicates
4942                // of this specific one, and remove them from the results.
4943                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4944                N = results.size();
4945                int j;
4946                for (j=specificsPos; j<N; j++) {
4947                    ResolveInfo sri = results.get(j);
4948                    if ((sri.activityInfo.name.equals(comp.getClassName())
4949                            && sri.activityInfo.applicationInfo.packageName.equals(
4950                                    comp.getPackageName()))
4951                        || (action != null && sri.filter.matchAction(action))) {
4952                        results.remove(j);
4953                        if (DEBUG_INTENT_MATCHING) Log.v(
4954                            TAG, "Removing duplicate item from " + j
4955                            + " due to specific " + specificsPos);
4956                        if (ri == null) {
4957                            ri = sri;
4958                        }
4959                        j--;
4960                        N--;
4961                    }
4962                }
4963
4964                // Add this specific item to its proper place.
4965                if (ri == null) {
4966                    ri = new ResolveInfo();
4967                    ri.activityInfo = ai;
4968                }
4969                results.add(specificsPos, ri);
4970                ri.specificIndex = i;
4971                specificsPos++;
4972            }
4973        }
4974
4975        // Now we go through the remaining generic results and remove any
4976        // duplicate actions that are found here.
4977        N = results.size();
4978        for (int i=specificsPos; i<N-1; i++) {
4979            final ResolveInfo rii = results.get(i);
4980            if (rii.filter == null) {
4981                continue;
4982            }
4983
4984            // Iterate over all of the actions of this result's intent
4985            // filter...  typically this should be just one.
4986            final Iterator<String> it = rii.filter.actionsIterator();
4987            if (it == null) {
4988                continue;
4989            }
4990            while (it.hasNext()) {
4991                final String action = it.next();
4992                if (resultsAction != null && resultsAction.equals(action)) {
4993                    // If this action was explicitly requested, then don't
4994                    // remove things that have it.
4995                    continue;
4996                }
4997                for (int j=i+1; j<N; j++) {
4998                    final ResolveInfo rij = results.get(j);
4999                    if (rij.filter != null && rij.filter.hasAction(action)) {
5000                        results.remove(j);
5001                        if (DEBUG_INTENT_MATCHING) Log.v(
5002                            TAG, "Removing duplicate item from " + j
5003                            + " due to action " + action + " at " + i);
5004                        j--;
5005                        N--;
5006                    }
5007                }
5008            }
5009
5010            // If the caller didn't request filter information, drop it now
5011            // so we don't have to marshall/unmarshall it.
5012            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5013                rii.filter = null;
5014            }
5015        }
5016
5017        // Filter out the caller activity if so requested.
5018        if (caller != null) {
5019            N = results.size();
5020            for (int i=0; i<N; i++) {
5021                ActivityInfo ainfo = results.get(i).activityInfo;
5022                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5023                        && caller.getClassName().equals(ainfo.name)) {
5024                    results.remove(i);
5025                    break;
5026                }
5027            }
5028        }
5029
5030        // If the caller didn't request filter information,
5031        // drop them now so we don't have to
5032        // marshall/unmarshall it.
5033        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5034            N = results.size();
5035            for (int i=0; i<N; i++) {
5036                results.get(i).filter = null;
5037            }
5038        }
5039
5040        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5041        return results;
5042    }
5043
5044    @Override
5045    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5046            int userId) {
5047        if (!sUserManager.exists(userId)) return Collections.emptyList();
5048        ComponentName comp = intent.getComponent();
5049        if (comp == null) {
5050            if (intent.getSelector() != null) {
5051                intent = intent.getSelector();
5052                comp = intent.getComponent();
5053            }
5054        }
5055        if (comp != null) {
5056            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5057            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5058            if (ai != null) {
5059                ResolveInfo ri = new ResolveInfo();
5060                ri.activityInfo = ai;
5061                list.add(ri);
5062            }
5063            return list;
5064        }
5065
5066        // reader
5067        synchronized (mPackages) {
5068            String pkgName = intent.getPackage();
5069            if (pkgName == null) {
5070                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5071            }
5072            final PackageParser.Package pkg = mPackages.get(pkgName);
5073            if (pkg != null) {
5074                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5075                        userId);
5076            }
5077            return null;
5078        }
5079    }
5080
5081    @Override
5082    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5083        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5084        if (!sUserManager.exists(userId)) return null;
5085        if (query != null) {
5086            if (query.size() >= 1) {
5087                // If there is more than one service with the same priority,
5088                // just arbitrarily pick the first one.
5089                return query.get(0);
5090            }
5091        }
5092        return null;
5093    }
5094
5095    @Override
5096    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5097            int userId) {
5098        if (!sUserManager.exists(userId)) return Collections.emptyList();
5099        ComponentName comp = intent.getComponent();
5100        if (comp == null) {
5101            if (intent.getSelector() != null) {
5102                intent = intent.getSelector();
5103                comp = intent.getComponent();
5104            }
5105        }
5106        if (comp != null) {
5107            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5108            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5109            if (si != null) {
5110                final ResolveInfo ri = new ResolveInfo();
5111                ri.serviceInfo = si;
5112                list.add(ri);
5113            }
5114            return list;
5115        }
5116
5117        // reader
5118        synchronized (mPackages) {
5119            String pkgName = intent.getPackage();
5120            if (pkgName == null) {
5121                return mServices.queryIntent(intent, resolvedType, flags, userId);
5122            }
5123            final PackageParser.Package pkg = mPackages.get(pkgName);
5124            if (pkg != null) {
5125                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5126                        userId);
5127            }
5128            return null;
5129        }
5130    }
5131
5132    @Override
5133    public List<ResolveInfo> queryIntentContentProviders(
5134            Intent intent, String resolvedType, int flags, int userId) {
5135        if (!sUserManager.exists(userId)) return Collections.emptyList();
5136        ComponentName comp = intent.getComponent();
5137        if (comp == null) {
5138            if (intent.getSelector() != null) {
5139                intent = intent.getSelector();
5140                comp = intent.getComponent();
5141            }
5142        }
5143        if (comp != null) {
5144            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5145            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5146            if (pi != null) {
5147                final ResolveInfo ri = new ResolveInfo();
5148                ri.providerInfo = pi;
5149                list.add(ri);
5150            }
5151            return list;
5152        }
5153
5154        // reader
5155        synchronized (mPackages) {
5156            String pkgName = intent.getPackage();
5157            if (pkgName == null) {
5158                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5159            }
5160            final PackageParser.Package pkg = mPackages.get(pkgName);
5161            if (pkg != null) {
5162                return mProviders.queryIntentForPackage(
5163                        intent, resolvedType, flags, pkg.providers, userId);
5164            }
5165            return null;
5166        }
5167    }
5168
5169    @Override
5170    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5171        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5172
5173        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5174
5175        // writer
5176        synchronized (mPackages) {
5177            ArrayList<PackageInfo> list;
5178            if (listUninstalled) {
5179                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5180                for (PackageSetting ps : mSettings.mPackages.values()) {
5181                    PackageInfo pi;
5182                    if (ps.pkg != null) {
5183                        pi = generatePackageInfo(ps.pkg, flags, userId);
5184                    } else {
5185                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5186                    }
5187                    if (pi != null) {
5188                        list.add(pi);
5189                    }
5190                }
5191            } else {
5192                list = new ArrayList<PackageInfo>(mPackages.size());
5193                for (PackageParser.Package p : mPackages.values()) {
5194                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5195                    if (pi != null) {
5196                        list.add(pi);
5197                    }
5198                }
5199            }
5200
5201            return new ParceledListSlice<PackageInfo>(list);
5202        }
5203    }
5204
5205    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5206            String[] permissions, boolean[] tmp, int flags, int userId) {
5207        int numMatch = 0;
5208        final PermissionsState permissionsState = ps.getPermissionsState();
5209        for (int i=0; i<permissions.length; i++) {
5210            final String permission = permissions[i];
5211            if (permissionsState.hasPermission(permission, userId)) {
5212                tmp[i] = true;
5213                numMatch++;
5214            } else {
5215                tmp[i] = false;
5216            }
5217        }
5218        if (numMatch == 0) {
5219            return;
5220        }
5221        PackageInfo pi;
5222        if (ps.pkg != null) {
5223            pi = generatePackageInfo(ps.pkg, flags, userId);
5224        } else {
5225            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5226        }
5227        // The above might return null in cases of uninstalled apps or install-state
5228        // skew across users/profiles.
5229        if (pi != null) {
5230            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5231                if (numMatch == permissions.length) {
5232                    pi.requestedPermissions = permissions;
5233                } else {
5234                    pi.requestedPermissions = new String[numMatch];
5235                    numMatch = 0;
5236                    for (int i=0; i<permissions.length; i++) {
5237                        if (tmp[i]) {
5238                            pi.requestedPermissions[numMatch] = permissions[i];
5239                            numMatch++;
5240                        }
5241                    }
5242                }
5243            }
5244            list.add(pi);
5245        }
5246    }
5247
5248    @Override
5249    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5250            String[] permissions, int flags, int userId) {
5251        if (!sUserManager.exists(userId)) return null;
5252        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5253
5254        // writer
5255        synchronized (mPackages) {
5256            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5257            boolean[] tmpBools = new boolean[permissions.length];
5258            if (listUninstalled) {
5259                for (PackageSetting ps : mSettings.mPackages.values()) {
5260                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5261                }
5262            } else {
5263                for (PackageParser.Package pkg : mPackages.values()) {
5264                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5265                    if (ps != null) {
5266                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5267                                userId);
5268                    }
5269                }
5270            }
5271
5272            return new ParceledListSlice<PackageInfo>(list);
5273        }
5274    }
5275
5276    @Override
5277    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5278        if (!sUserManager.exists(userId)) return null;
5279        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5280
5281        // writer
5282        synchronized (mPackages) {
5283            ArrayList<ApplicationInfo> list;
5284            if (listUninstalled) {
5285                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5286                for (PackageSetting ps : mSettings.mPackages.values()) {
5287                    ApplicationInfo ai;
5288                    if (ps.pkg != null) {
5289                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5290                                ps.readUserState(userId), userId);
5291                    } else {
5292                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5293                    }
5294                    if (ai != null) {
5295                        list.add(ai);
5296                    }
5297                }
5298            } else {
5299                list = new ArrayList<ApplicationInfo>(mPackages.size());
5300                for (PackageParser.Package p : mPackages.values()) {
5301                    if (p.mExtras != null) {
5302                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5303                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5304                        if (ai != null) {
5305                            list.add(ai);
5306                        }
5307                    }
5308                }
5309            }
5310
5311            return new ParceledListSlice<ApplicationInfo>(list);
5312        }
5313    }
5314
5315    public List<ApplicationInfo> getPersistentApplications(int flags) {
5316        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5317
5318        // reader
5319        synchronized (mPackages) {
5320            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5321            final int userId = UserHandle.getCallingUserId();
5322            while (i.hasNext()) {
5323                final PackageParser.Package p = i.next();
5324                if (p.applicationInfo != null
5325                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5326                        && (!mSafeMode || isSystemApp(p))) {
5327                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5328                    if (ps != null) {
5329                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5330                                ps.readUserState(userId), userId);
5331                        if (ai != null) {
5332                            finalList.add(ai);
5333                        }
5334                    }
5335                }
5336            }
5337        }
5338
5339        return finalList;
5340    }
5341
5342    @Override
5343    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return null;
5345        // reader
5346        synchronized (mPackages) {
5347            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5348            PackageSetting ps = provider != null
5349                    ? mSettings.mPackages.get(provider.owner.packageName)
5350                    : null;
5351            return ps != null
5352                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5353                    && (!mSafeMode || (provider.info.applicationInfo.flags
5354                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5355                    ? PackageParser.generateProviderInfo(provider, flags,
5356                            ps.readUserState(userId), userId)
5357                    : null;
5358        }
5359    }
5360
5361    /**
5362     * @deprecated
5363     */
5364    @Deprecated
5365    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5366        // reader
5367        synchronized (mPackages) {
5368            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5369                    .entrySet().iterator();
5370            final int userId = UserHandle.getCallingUserId();
5371            while (i.hasNext()) {
5372                Map.Entry<String, PackageParser.Provider> entry = i.next();
5373                PackageParser.Provider p = entry.getValue();
5374                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5375
5376                if (ps != null && p.syncable
5377                        && (!mSafeMode || (p.info.applicationInfo.flags
5378                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5379                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5380                            ps.readUserState(userId), userId);
5381                    if (info != null) {
5382                        outNames.add(entry.getKey());
5383                        outInfo.add(info);
5384                    }
5385                }
5386            }
5387        }
5388    }
5389
5390    @Override
5391    public List<ProviderInfo> queryContentProviders(String processName,
5392            int uid, int flags) {
5393        ArrayList<ProviderInfo> finalList = null;
5394        // reader
5395        synchronized (mPackages) {
5396            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5397            final int userId = processName != null ?
5398                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5399            while (i.hasNext()) {
5400                final PackageParser.Provider p = i.next();
5401                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5402                if (ps != null && p.info.authority != null
5403                        && (processName == null
5404                                || (p.info.processName.equals(processName)
5405                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5406                        && mSettings.isEnabledLPr(p.info, flags, userId)
5407                        && (!mSafeMode
5408                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5409                    if (finalList == null) {
5410                        finalList = new ArrayList<ProviderInfo>(3);
5411                    }
5412                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5413                            ps.readUserState(userId), userId);
5414                    if (info != null) {
5415                        finalList.add(info);
5416                    }
5417                }
5418            }
5419        }
5420
5421        if (finalList != null) {
5422            Collections.sort(finalList, mProviderInitOrderSorter);
5423        }
5424
5425        return finalList;
5426    }
5427
5428    @Override
5429    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5430            int flags) {
5431        // reader
5432        synchronized (mPackages) {
5433            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5434            return PackageParser.generateInstrumentationInfo(i, flags);
5435        }
5436    }
5437
5438    @Override
5439    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5440            int flags) {
5441        ArrayList<InstrumentationInfo> finalList =
5442            new ArrayList<InstrumentationInfo>();
5443
5444        // reader
5445        synchronized (mPackages) {
5446            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5447            while (i.hasNext()) {
5448                final PackageParser.Instrumentation p = i.next();
5449                if (targetPackage == null
5450                        || targetPackage.equals(p.info.targetPackage)) {
5451                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5452                            flags);
5453                    if (ii != null) {
5454                        finalList.add(ii);
5455                    }
5456                }
5457            }
5458        }
5459
5460        return finalList;
5461    }
5462
5463    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5464        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5465        if (overlays == null) {
5466            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5467            return;
5468        }
5469        for (PackageParser.Package opkg : overlays.values()) {
5470            // Not much to do if idmap fails: we already logged the error
5471            // and we certainly don't want to abort installation of pkg simply
5472            // because an overlay didn't fit properly. For these reasons,
5473            // ignore the return value of createIdmapForPackagePairLI.
5474            createIdmapForPackagePairLI(pkg, opkg);
5475        }
5476    }
5477
5478    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5479            PackageParser.Package opkg) {
5480        if (!opkg.mTrustedOverlay) {
5481            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5482                    opkg.baseCodePath + ": overlay not trusted");
5483            return false;
5484        }
5485        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5486        if (overlaySet == null) {
5487            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5488                    opkg.baseCodePath + " but target package has no known overlays");
5489            return false;
5490        }
5491        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5492        // TODO: generate idmap for split APKs
5493        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5494            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5495                    + opkg.baseCodePath);
5496            return false;
5497        }
5498        PackageParser.Package[] overlayArray =
5499            overlaySet.values().toArray(new PackageParser.Package[0]);
5500        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5501            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5502                return p1.mOverlayPriority - p2.mOverlayPriority;
5503            }
5504        };
5505        Arrays.sort(overlayArray, cmp);
5506
5507        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5508        int i = 0;
5509        for (PackageParser.Package p : overlayArray) {
5510            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5511        }
5512        return true;
5513    }
5514
5515    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5516        final File[] files = dir.listFiles();
5517        if (ArrayUtils.isEmpty(files)) {
5518            Log.d(TAG, "No files in app dir " + dir);
5519            return;
5520        }
5521
5522        if (DEBUG_PACKAGE_SCANNING) {
5523            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5524                    + " flags=0x" + Integer.toHexString(parseFlags));
5525        }
5526
5527        for (File file : files) {
5528            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5529                    && !PackageInstallerService.isStageName(file.getName());
5530            if (!isPackage) {
5531                // Ignore entries which are not packages
5532                continue;
5533            }
5534            try {
5535                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5536                        scanFlags, currentTime, null);
5537            } catch (PackageManagerException e) {
5538                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5539
5540                // Delete invalid userdata apps
5541                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5542                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5543                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5544                    if (file.isDirectory()) {
5545                        mInstaller.rmPackageDir(file.getAbsolutePath());
5546                    } else {
5547                        file.delete();
5548                    }
5549                }
5550            }
5551        }
5552    }
5553
5554    private static File getSettingsProblemFile() {
5555        File dataDir = Environment.getDataDirectory();
5556        File systemDir = new File(dataDir, "system");
5557        File fname = new File(systemDir, "uiderrors.txt");
5558        return fname;
5559    }
5560
5561    static void reportSettingsProblem(int priority, String msg) {
5562        logCriticalInfo(priority, msg);
5563    }
5564
5565    static void logCriticalInfo(int priority, String msg) {
5566        Slog.println(priority, TAG, msg);
5567        EventLogTags.writePmCriticalInfo(msg);
5568        try {
5569            File fname = getSettingsProblemFile();
5570            FileOutputStream out = new FileOutputStream(fname, true);
5571            PrintWriter pw = new FastPrintWriter(out);
5572            SimpleDateFormat formatter = new SimpleDateFormat();
5573            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5574            pw.println(dateString + ": " + msg);
5575            pw.close();
5576            FileUtils.setPermissions(
5577                    fname.toString(),
5578                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5579                    -1, -1);
5580        } catch (java.io.IOException e) {
5581        }
5582    }
5583
5584    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5585            PackageParser.Package pkg, File srcFile, int parseFlags)
5586            throws PackageManagerException {
5587        if (ps != null
5588                && ps.codePath.equals(srcFile)
5589                && ps.timeStamp == srcFile.lastModified()
5590                && !isCompatSignatureUpdateNeeded(pkg)
5591                && !isRecoverSignatureUpdateNeeded(pkg)) {
5592            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5593            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5594            ArraySet<PublicKey> signingKs;
5595            synchronized (mPackages) {
5596                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5597            }
5598            if (ps.signatures.mSignatures != null
5599                    && ps.signatures.mSignatures.length != 0
5600                    && signingKs != null) {
5601                // Optimization: reuse the existing cached certificates
5602                // if the package appears to be unchanged.
5603                pkg.mSignatures = ps.signatures.mSignatures;
5604                pkg.mSigningKeys = signingKs;
5605                return;
5606            }
5607
5608            Slog.w(TAG, "PackageSetting for " + ps.name
5609                    + " is missing signatures.  Collecting certs again to recover them.");
5610        } else {
5611            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5612        }
5613
5614        try {
5615            pp.collectCertificates(pkg, parseFlags);
5616            pp.collectManifestDigest(pkg);
5617        } catch (PackageParserException e) {
5618            throw PackageManagerException.from(e);
5619        }
5620    }
5621
5622    /*
5623     *  Scan a package and return the newly parsed package.
5624     *  Returns null in case of errors and the error code is stored in mLastScanError
5625     */
5626    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5627            long currentTime, UserHandle user) throws PackageManagerException {
5628        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5629        parseFlags |= mDefParseFlags;
5630        PackageParser pp = new PackageParser();
5631        pp.setSeparateProcesses(mSeparateProcesses);
5632        pp.setOnlyCoreApps(mOnlyCore);
5633        pp.setDisplayMetrics(mMetrics);
5634
5635        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5636            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5637        }
5638
5639        final PackageParser.Package pkg;
5640        try {
5641            pkg = pp.parsePackage(scanFile, parseFlags);
5642        } catch (PackageParserException e) {
5643            throw PackageManagerException.from(e);
5644        }
5645
5646        PackageSetting ps = null;
5647        PackageSetting updatedPkg;
5648        // reader
5649        synchronized (mPackages) {
5650            // Look to see if we already know about this package.
5651            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5652            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5653                // This package has been renamed to its original name.  Let's
5654                // use that.
5655                ps = mSettings.peekPackageLPr(oldName);
5656            }
5657            // If there was no original package, see one for the real package name.
5658            if (ps == null) {
5659                ps = mSettings.peekPackageLPr(pkg.packageName);
5660            }
5661            // Check to see if this package could be hiding/updating a system
5662            // package.  Must look for it either under the original or real
5663            // package name depending on our state.
5664            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5665            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5666        }
5667        boolean updatedPkgBetter = false;
5668        // First check if this is a system package that may involve an update
5669        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5670            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5671            // it needs to drop FLAG_PRIVILEGED.
5672            if (locationIsPrivileged(scanFile)) {
5673                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5674            } else {
5675                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5676            }
5677
5678            if (ps != null && !ps.codePath.equals(scanFile)) {
5679                // The path has changed from what was last scanned...  check the
5680                // version of the new path against what we have stored to determine
5681                // what to do.
5682                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5683                if (pkg.mVersionCode <= ps.versionCode) {
5684                    // The system package has been updated and the code path does not match
5685                    // Ignore entry. Skip it.
5686                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5687                            + " ignored: updated version " + ps.versionCode
5688                            + " better than this " + pkg.mVersionCode);
5689                    if (!updatedPkg.codePath.equals(scanFile)) {
5690                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5691                                + ps.name + " changing from " + updatedPkg.codePathString
5692                                + " to " + scanFile);
5693                        updatedPkg.codePath = scanFile;
5694                        updatedPkg.codePathString = scanFile.toString();
5695                        updatedPkg.resourcePath = scanFile;
5696                        updatedPkg.resourcePathString = scanFile.toString();
5697                    }
5698                    updatedPkg.pkg = pkg;
5699                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5700                            "Package " + ps.name + " at " + scanFile
5701                                    + " ignored: updated version " + ps.versionCode
5702                                    + " better than this " + pkg.mVersionCode);
5703                } else {
5704                    // The current app on the system partition is better than
5705                    // what we have updated to on the data partition; switch
5706                    // back to the system partition version.
5707                    // At this point, its safely assumed that package installation for
5708                    // apps in system partition will go through. If not there won't be a working
5709                    // version of the app
5710                    // writer
5711                    synchronized (mPackages) {
5712                        // Just remove the loaded entries from package lists.
5713                        mPackages.remove(ps.name);
5714                    }
5715
5716                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5717                            + " reverting from " + ps.codePathString
5718                            + ": new version " + pkg.mVersionCode
5719                            + " better than installed " + ps.versionCode);
5720
5721                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5722                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5723                    synchronized (mInstallLock) {
5724                        args.cleanUpResourcesLI();
5725                    }
5726                    synchronized (mPackages) {
5727                        mSettings.enableSystemPackageLPw(ps.name);
5728                    }
5729                    updatedPkgBetter = true;
5730                }
5731            }
5732        }
5733
5734        if (updatedPkg != null) {
5735            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5736            // initially
5737            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5738
5739            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5740            // flag set initially
5741            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5742                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5743            }
5744        }
5745
5746        // Verify certificates against what was last scanned
5747        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5748
5749        /*
5750         * A new system app appeared, but we already had a non-system one of the
5751         * same name installed earlier.
5752         */
5753        boolean shouldHideSystemApp = false;
5754        if (updatedPkg == null && ps != null
5755                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5756            /*
5757             * Check to make sure the signatures match first. If they don't,
5758             * wipe the installed application and its data.
5759             */
5760            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5761                    != PackageManager.SIGNATURE_MATCH) {
5762                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5763                        + " signatures don't match existing userdata copy; removing");
5764                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5765                ps = null;
5766            } else {
5767                /*
5768                 * If the newly-added system app is an older version than the
5769                 * already installed version, hide it. It will be scanned later
5770                 * and re-added like an update.
5771                 */
5772                if (pkg.mVersionCode <= ps.versionCode) {
5773                    shouldHideSystemApp = true;
5774                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5775                            + " but new version " + pkg.mVersionCode + " better than installed "
5776                            + ps.versionCode + "; hiding system");
5777                } else {
5778                    /*
5779                     * The newly found system app is a newer version that the
5780                     * one previously installed. Simply remove the
5781                     * already-installed application and replace it with our own
5782                     * while keeping the application data.
5783                     */
5784                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5785                            + " reverting from " + ps.codePathString + ": new version "
5786                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5787                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5788                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5789                    synchronized (mInstallLock) {
5790                        args.cleanUpResourcesLI();
5791                    }
5792                }
5793            }
5794        }
5795
5796        // The apk is forward locked (not public) if its code and resources
5797        // are kept in different files. (except for app in either system or
5798        // vendor path).
5799        // TODO grab this value from PackageSettings
5800        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5801            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5802                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5803            }
5804        }
5805
5806        // TODO: extend to support forward-locked splits
5807        String resourcePath = null;
5808        String baseResourcePath = null;
5809        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5810            if (ps != null && ps.resourcePathString != null) {
5811                resourcePath = ps.resourcePathString;
5812                baseResourcePath = ps.resourcePathString;
5813            } else {
5814                // Should not happen at all. Just log an error.
5815                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5816            }
5817        } else {
5818            resourcePath = pkg.codePath;
5819            baseResourcePath = pkg.baseCodePath;
5820        }
5821
5822        // Set application objects path explicitly.
5823        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5824        pkg.applicationInfo.setCodePath(pkg.codePath);
5825        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5826        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5827        pkg.applicationInfo.setResourcePath(resourcePath);
5828        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5829        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5830
5831        // Note that we invoke the following method only if we are about to unpack an application
5832        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5833                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5834
5835        /*
5836         * If the system app should be overridden by a previously installed
5837         * data, hide the system app now and let the /data/app scan pick it up
5838         * again.
5839         */
5840        if (shouldHideSystemApp) {
5841            synchronized (mPackages) {
5842                /*
5843                 * We have to grant systems permissions before we hide, because
5844                 * grantPermissions will assume the package update is trying to
5845                 * expand its permissions.
5846                 */
5847                grantPermissionsLPw(pkg, true, pkg.packageName);
5848                mSettings.disableSystemPackageLPw(pkg.packageName);
5849            }
5850        }
5851
5852        return scannedPkg;
5853    }
5854
5855    private static String fixProcessName(String defProcessName,
5856            String processName, int uid) {
5857        if (processName == null) {
5858            return defProcessName;
5859        }
5860        return processName;
5861    }
5862
5863    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5864            throws PackageManagerException {
5865        if (pkgSetting.signatures.mSignatures != null) {
5866            // Already existing package. Make sure signatures match
5867            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5868                    == PackageManager.SIGNATURE_MATCH;
5869            if (!match) {
5870                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5871                        == PackageManager.SIGNATURE_MATCH;
5872            }
5873            if (!match) {
5874                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5875                        == PackageManager.SIGNATURE_MATCH;
5876            }
5877            if (!match) {
5878                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5879                        + pkg.packageName + " signatures do not match the "
5880                        + "previously installed version; ignoring!");
5881            }
5882        }
5883
5884        // Check for shared user signatures
5885        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5886            // Already existing package. Make sure signatures match
5887            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5888                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5889            if (!match) {
5890                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5891                        == PackageManager.SIGNATURE_MATCH;
5892            }
5893            if (!match) {
5894                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5895                        == PackageManager.SIGNATURE_MATCH;
5896            }
5897            if (!match) {
5898                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5899                        "Package " + pkg.packageName
5900                        + " has no signatures that match those in shared user "
5901                        + pkgSetting.sharedUser.name + "; ignoring!");
5902            }
5903        }
5904    }
5905
5906    /**
5907     * Enforces that only the system UID or root's UID can call a method exposed
5908     * via Binder.
5909     *
5910     * @param message used as message if SecurityException is thrown
5911     * @throws SecurityException if the caller is not system or root
5912     */
5913    private static final void enforceSystemOrRoot(String message) {
5914        final int uid = Binder.getCallingUid();
5915        if (uid != Process.SYSTEM_UID && uid != 0) {
5916            throw new SecurityException(message);
5917        }
5918    }
5919
5920    @Override
5921    public void performBootDexOpt() {
5922        enforceSystemOrRoot("Only the system can request dexopt be performed");
5923
5924        // Before everything else, see whether we need to fstrim.
5925        try {
5926            IMountService ms = PackageHelper.getMountService();
5927            if (ms != null) {
5928                final boolean isUpgrade = isUpgrade();
5929                boolean doTrim = isUpgrade;
5930                if (doTrim) {
5931                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5932                } else {
5933                    final long interval = android.provider.Settings.Global.getLong(
5934                            mContext.getContentResolver(),
5935                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5936                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5937                    if (interval > 0) {
5938                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5939                        if (timeSinceLast > interval) {
5940                            doTrim = true;
5941                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5942                                    + "; running immediately");
5943                        }
5944                    }
5945                }
5946                if (doTrim) {
5947                    if (!isFirstBoot()) {
5948                        try {
5949                            ActivityManagerNative.getDefault().showBootMessage(
5950                                    mContext.getResources().getString(
5951                                            R.string.android_upgrading_fstrim), true);
5952                        } catch (RemoteException e) {
5953                        }
5954                    }
5955                    ms.runMaintenance();
5956                }
5957            } else {
5958                Slog.e(TAG, "Mount service unavailable!");
5959            }
5960        } catch (RemoteException e) {
5961            // Can't happen; MountService is local
5962        }
5963
5964        final ArraySet<PackageParser.Package> pkgs;
5965        synchronized (mPackages) {
5966            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5967        }
5968
5969        if (pkgs != null) {
5970            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5971            // in case the device runs out of space.
5972            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5973            // Give priority to core apps.
5974            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5975                PackageParser.Package pkg = it.next();
5976                if (pkg.coreApp) {
5977                    if (DEBUG_DEXOPT) {
5978                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5979                    }
5980                    sortedPkgs.add(pkg);
5981                    it.remove();
5982                }
5983            }
5984            // Give priority to system apps that listen for pre boot complete.
5985            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5986            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5987            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5988                PackageParser.Package pkg = it.next();
5989                if (pkgNames.contains(pkg.packageName)) {
5990                    if (DEBUG_DEXOPT) {
5991                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5992                    }
5993                    sortedPkgs.add(pkg);
5994                    it.remove();
5995                }
5996            }
5997            // Give priority to system apps.
5998            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5999                PackageParser.Package pkg = it.next();
6000                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6001                    if (DEBUG_DEXOPT) {
6002                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6003                    }
6004                    sortedPkgs.add(pkg);
6005                    it.remove();
6006                }
6007            }
6008            // Give priority to updated system apps.
6009            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6010                PackageParser.Package pkg = it.next();
6011                if (pkg.isUpdatedSystemApp()) {
6012                    if (DEBUG_DEXOPT) {
6013                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6014                    }
6015                    sortedPkgs.add(pkg);
6016                    it.remove();
6017                }
6018            }
6019            // Give priority to apps that listen for boot complete.
6020            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6021            pkgNames = getPackageNamesForIntent(intent);
6022            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6023                PackageParser.Package pkg = it.next();
6024                if (pkgNames.contains(pkg.packageName)) {
6025                    if (DEBUG_DEXOPT) {
6026                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6027                    }
6028                    sortedPkgs.add(pkg);
6029                    it.remove();
6030                }
6031            }
6032            // Filter out packages that aren't recently used.
6033            filterRecentlyUsedApps(pkgs);
6034            // Add all remaining apps.
6035            for (PackageParser.Package pkg : pkgs) {
6036                if (DEBUG_DEXOPT) {
6037                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6038                }
6039                sortedPkgs.add(pkg);
6040            }
6041
6042            // If we want to be lazy, filter everything that wasn't recently used.
6043            if (mLazyDexOpt) {
6044                filterRecentlyUsedApps(sortedPkgs);
6045            }
6046
6047            int i = 0;
6048            int total = sortedPkgs.size();
6049            File dataDir = Environment.getDataDirectory();
6050            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6051            if (lowThreshold == 0) {
6052                throw new IllegalStateException("Invalid low memory threshold");
6053            }
6054            for (PackageParser.Package pkg : sortedPkgs) {
6055                long usableSpace = dataDir.getUsableSpace();
6056                if (usableSpace < lowThreshold) {
6057                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6058                    break;
6059                }
6060                performBootDexOpt(pkg, ++i, total);
6061            }
6062        }
6063    }
6064
6065    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6066        // Filter out packages that aren't recently used.
6067        //
6068        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6069        // should do a full dexopt.
6070        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6071            int total = pkgs.size();
6072            int skipped = 0;
6073            long now = System.currentTimeMillis();
6074            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6075                PackageParser.Package pkg = i.next();
6076                long then = pkg.mLastPackageUsageTimeInMills;
6077                if (then + mDexOptLRUThresholdInMills < now) {
6078                    if (DEBUG_DEXOPT) {
6079                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6080                              ((then == 0) ? "never" : new Date(then)));
6081                    }
6082                    i.remove();
6083                    skipped++;
6084                }
6085            }
6086            if (DEBUG_DEXOPT) {
6087                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6088            }
6089        }
6090    }
6091
6092    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6093        List<ResolveInfo> ris = null;
6094        try {
6095            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6096                    intent, null, 0, UserHandle.USER_OWNER);
6097        } catch (RemoteException e) {
6098        }
6099        ArraySet<String> pkgNames = new ArraySet<String>();
6100        if (ris != null) {
6101            for (ResolveInfo ri : ris) {
6102                pkgNames.add(ri.activityInfo.packageName);
6103            }
6104        }
6105        return pkgNames;
6106    }
6107
6108    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6109        if (DEBUG_DEXOPT) {
6110            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6111        }
6112        if (!isFirstBoot()) {
6113            try {
6114                ActivityManagerNative.getDefault().showBootMessage(
6115                        mContext.getResources().getString(R.string.android_upgrading_apk,
6116                                curr, total), true);
6117            } catch (RemoteException e) {
6118            }
6119        }
6120        PackageParser.Package p = pkg;
6121        synchronized (mInstallLock) {
6122            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6123                    false /* force dex */, false /* defer */, true /* include dependencies */);
6124        }
6125    }
6126
6127    @Override
6128    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6129        return performDexOpt(packageName, instructionSet, false);
6130    }
6131
6132    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6133        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6134        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6135        if (!dexopt && !updateUsage) {
6136            // We aren't going to dexopt or update usage, so bail early.
6137            return false;
6138        }
6139        PackageParser.Package p;
6140        final String targetInstructionSet;
6141        synchronized (mPackages) {
6142            p = mPackages.get(packageName);
6143            if (p == null) {
6144                return false;
6145            }
6146            if (updateUsage) {
6147                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6148            }
6149            mPackageUsage.write(false);
6150            if (!dexopt) {
6151                // We aren't going to dexopt, so bail early.
6152                return false;
6153            }
6154
6155            targetInstructionSet = instructionSet != null ? instructionSet :
6156                    getPrimaryInstructionSet(p.applicationInfo);
6157            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6158                return false;
6159            }
6160        }
6161
6162        synchronized (mInstallLock) {
6163            final String[] instructionSets = new String[] { targetInstructionSet };
6164            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6165                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6166            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6167        }
6168    }
6169
6170    public ArraySet<String> getPackagesThatNeedDexOpt() {
6171        ArraySet<String> pkgs = null;
6172        synchronized (mPackages) {
6173            for (PackageParser.Package p : mPackages.values()) {
6174                if (DEBUG_DEXOPT) {
6175                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6176                }
6177                if (!p.mDexOptPerformed.isEmpty()) {
6178                    continue;
6179                }
6180                if (pkgs == null) {
6181                    pkgs = new ArraySet<String>();
6182                }
6183                pkgs.add(p.packageName);
6184            }
6185        }
6186        return pkgs;
6187    }
6188
6189    public void shutdown() {
6190        mPackageUsage.write(true);
6191    }
6192
6193    @Override
6194    public void forceDexOpt(String packageName) {
6195        enforceSystemOrRoot("forceDexOpt");
6196
6197        PackageParser.Package pkg;
6198        synchronized (mPackages) {
6199            pkg = mPackages.get(packageName);
6200            if (pkg == null) {
6201                throw new IllegalArgumentException("Missing package: " + packageName);
6202            }
6203        }
6204
6205        synchronized (mInstallLock) {
6206            final String[] instructionSets = new String[] {
6207                    getPrimaryInstructionSet(pkg.applicationInfo) };
6208            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6209                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6210            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6211                throw new IllegalStateException("Failed to dexopt: " + res);
6212            }
6213        }
6214    }
6215
6216    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6217        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6218            Slog.w(TAG, "Unable to update from " + oldPkg.name
6219                    + " to " + newPkg.packageName
6220                    + ": old package not in system partition");
6221            return false;
6222        } else if (mPackages.get(oldPkg.name) != null) {
6223            Slog.w(TAG, "Unable to update from " + oldPkg.name
6224                    + " to " + newPkg.packageName
6225                    + ": old package still exists");
6226            return false;
6227        }
6228        return true;
6229    }
6230
6231    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6232        int[] users = sUserManager.getUserIds();
6233        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6234        if (res < 0) {
6235            return res;
6236        }
6237        for (int user : users) {
6238            if (user != 0) {
6239                res = mInstaller.createUserData(volumeUuid, packageName,
6240                        UserHandle.getUid(user, uid), user, seinfo);
6241                if (res < 0) {
6242                    return res;
6243                }
6244            }
6245        }
6246        return res;
6247    }
6248
6249    private int removeDataDirsLI(String volumeUuid, String packageName) {
6250        int[] users = sUserManager.getUserIds();
6251        int res = 0;
6252        for (int user : users) {
6253            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6254            if (resInner < 0) {
6255                res = resInner;
6256            }
6257        }
6258
6259        return res;
6260    }
6261
6262    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6263        int[] users = sUserManager.getUserIds();
6264        int res = 0;
6265        for (int user : users) {
6266            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6267            if (resInner < 0) {
6268                res = resInner;
6269            }
6270        }
6271        return res;
6272    }
6273
6274    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6275            PackageParser.Package changingLib) {
6276        if (file.path != null) {
6277            usesLibraryFiles.add(file.path);
6278            return;
6279        }
6280        PackageParser.Package p = mPackages.get(file.apk);
6281        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6282            // If we are doing this while in the middle of updating a library apk,
6283            // then we need to make sure to use that new apk for determining the
6284            // dependencies here.  (We haven't yet finished committing the new apk
6285            // to the package manager state.)
6286            if (p == null || p.packageName.equals(changingLib.packageName)) {
6287                p = changingLib;
6288            }
6289        }
6290        if (p != null) {
6291            usesLibraryFiles.addAll(p.getAllCodePaths());
6292        }
6293    }
6294
6295    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6296            PackageParser.Package changingLib) throws PackageManagerException {
6297        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6298            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6299            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6300            for (int i=0; i<N; i++) {
6301                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6302                if (file == null) {
6303                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6304                            "Package " + pkg.packageName + " requires unavailable shared library "
6305                            + pkg.usesLibraries.get(i) + "; failing!");
6306                }
6307                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6308            }
6309            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6310            for (int i=0; i<N; i++) {
6311                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6312                if (file == null) {
6313                    Slog.w(TAG, "Package " + pkg.packageName
6314                            + " desires unavailable shared library "
6315                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6316                } else {
6317                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6318                }
6319            }
6320            N = usesLibraryFiles.size();
6321            if (N > 0) {
6322                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6323            } else {
6324                pkg.usesLibraryFiles = null;
6325            }
6326        }
6327    }
6328
6329    private static boolean hasString(List<String> list, List<String> which) {
6330        if (list == null) {
6331            return false;
6332        }
6333        for (int i=list.size()-1; i>=0; i--) {
6334            for (int j=which.size()-1; j>=0; j--) {
6335                if (which.get(j).equals(list.get(i))) {
6336                    return true;
6337                }
6338            }
6339        }
6340        return false;
6341    }
6342
6343    private void updateAllSharedLibrariesLPw() {
6344        for (PackageParser.Package pkg : mPackages.values()) {
6345            try {
6346                updateSharedLibrariesLPw(pkg, null);
6347            } catch (PackageManagerException e) {
6348                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6349            }
6350        }
6351    }
6352
6353    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6354            PackageParser.Package changingPkg) {
6355        ArrayList<PackageParser.Package> res = null;
6356        for (PackageParser.Package pkg : mPackages.values()) {
6357            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6358                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6359                if (res == null) {
6360                    res = new ArrayList<PackageParser.Package>();
6361                }
6362                res.add(pkg);
6363                try {
6364                    updateSharedLibrariesLPw(pkg, changingPkg);
6365                } catch (PackageManagerException e) {
6366                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6367                }
6368            }
6369        }
6370        return res;
6371    }
6372
6373    /**
6374     * Derive the value of the {@code cpuAbiOverride} based on the provided
6375     * value and an optional stored value from the package settings.
6376     */
6377    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6378        String cpuAbiOverride = null;
6379
6380        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6381            cpuAbiOverride = null;
6382        } else if (abiOverride != null) {
6383            cpuAbiOverride = abiOverride;
6384        } else if (settings != null) {
6385            cpuAbiOverride = settings.cpuAbiOverrideString;
6386        }
6387
6388        return cpuAbiOverride;
6389    }
6390
6391    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6392            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6393        boolean success = false;
6394        try {
6395            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6396                    currentTime, user);
6397            success = true;
6398            return res;
6399        } finally {
6400            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6401                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6402            }
6403        }
6404    }
6405
6406    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6407            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6408        final File scanFile = new File(pkg.codePath);
6409        if (pkg.applicationInfo.getCodePath() == null ||
6410                pkg.applicationInfo.getResourcePath() == null) {
6411            // Bail out. The resource and code paths haven't been set.
6412            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6413                    "Code and resource paths haven't been set correctly");
6414        }
6415
6416        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6417            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6418        } else {
6419            // Only allow system apps to be flagged as core apps.
6420            pkg.coreApp = false;
6421        }
6422
6423        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6424            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6425        }
6426
6427        if (mCustomResolverComponentName != null &&
6428                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6429            setUpCustomResolverActivity(pkg);
6430        }
6431
6432        if (pkg.packageName.equals("android")) {
6433            synchronized (mPackages) {
6434                if (mAndroidApplication != null) {
6435                    Slog.w(TAG, "*************************************************");
6436                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6437                    Slog.w(TAG, " file=" + scanFile);
6438                    Slog.w(TAG, "*************************************************");
6439                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6440                            "Core android package being redefined.  Skipping.");
6441                }
6442
6443                // Set up information for our fall-back user intent resolution activity.
6444                mPlatformPackage = pkg;
6445                pkg.mVersionCode = mSdkVersion;
6446                mAndroidApplication = pkg.applicationInfo;
6447
6448                if (!mResolverReplaced) {
6449                    mResolveActivity.applicationInfo = mAndroidApplication;
6450                    mResolveActivity.name = ResolverActivity.class.getName();
6451                    mResolveActivity.packageName = mAndroidApplication.packageName;
6452                    mResolveActivity.processName = "system:ui";
6453                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6454                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6455                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6456                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6457                    mResolveActivity.exported = true;
6458                    mResolveActivity.enabled = true;
6459                    mResolveInfo.activityInfo = mResolveActivity;
6460                    mResolveInfo.priority = 0;
6461                    mResolveInfo.preferredOrder = 0;
6462                    mResolveInfo.match = 0;
6463                    mResolveComponentName = new ComponentName(
6464                            mAndroidApplication.packageName, mResolveActivity.name);
6465                }
6466            }
6467        }
6468
6469        if (DEBUG_PACKAGE_SCANNING) {
6470            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6471                Log.d(TAG, "Scanning package " + pkg.packageName);
6472        }
6473
6474        if (mPackages.containsKey(pkg.packageName)
6475                || mSharedLibraries.containsKey(pkg.packageName)) {
6476            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6477                    "Application package " + pkg.packageName
6478                    + " already installed.  Skipping duplicate.");
6479        }
6480
6481        // If we're only installing presumed-existing packages, require that the
6482        // scanned APK is both already known and at the path previously established
6483        // for it.  Previously unknown packages we pick up normally, but if we have an
6484        // a priori expectation about this package's install presence, enforce it.
6485        // With a singular exception for new system packages. When an OTA contains
6486        // a new system package, we allow the codepath to change from a system location
6487        // to the user-installed location. If we don't allow this change, any newer,
6488        // user-installed version of the application will be ignored.
6489        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6490            if (mExpectingBetter.containsKey(pkg.packageName)) {
6491                logCriticalInfo(Log.WARN,
6492                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6493            } else {
6494                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6495                if (known != null) {
6496                    if (DEBUG_PACKAGE_SCANNING) {
6497                        Log.d(TAG, "Examining " + pkg.codePath
6498                                + " and requiring known paths " + known.codePathString
6499                                + " & " + known.resourcePathString);
6500                    }
6501                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6502                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6503                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6504                                "Application package " + pkg.packageName
6505                                + " found at " + pkg.applicationInfo.getCodePath()
6506                                + " but expected at " + known.codePathString + "; ignoring.");
6507                    }
6508                }
6509            }
6510        }
6511
6512        // Initialize package source and resource directories
6513        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6514        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6515
6516        SharedUserSetting suid = null;
6517        PackageSetting pkgSetting = null;
6518
6519        if (!isSystemApp(pkg)) {
6520            // Only system apps can use these features.
6521            pkg.mOriginalPackages = null;
6522            pkg.mRealPackage = null;
6523            pkg.mAdoptPermissions = null;
6524        }
6525
6526        // writer
6527        synchronized (mPackages) {
6528            if (pkg.mSharedUserId != null) {
6529                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6530                if (suid == null) {
6531                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6532                            "Creating application package " + pkg.packageName
6533                            + " for shared user failed");
6534                }
6535                if (DEBUG_PACKAGE_SCANNING) {
6536                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6537                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6538                                + "): packages=" + suid.packages);
6539                }
6540            }
6541
6542            // Check if we are renaming from an original package name.
6543            PackageSetting origPackage = null;
6544            String realName = null;
6545            if (pkg.mOriginalPackages != null) {
6546                // This package may need to be renamed to a previously
6547                // installed name.  Let's check on that...
6548                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6549                if (pkg.mOriginalPackages.contains(renamed)) {
6550                    // This package had originally been installed as the
6551                    // original name, and we have already taken care of
6552                    // transitioning to the new one.  Just update the new
6553                    // one to continue using the old name.
6554                    realName = pkg.mRealPackage;
6555                    if (!pkg.packageName.equals(renamed)) {
6556                        // Callers into this function may have already taken
6557                        // care of renaming the package; only do it here if
6558                        // it is not already done.
6559                        pkg.setPackageName(renamed);
6560                    }
6561
6562                } else {
6563                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6564                        if ((origPackage = mSettings.peekPackageLPr(
6565                                pkg.mOriginalPackages.get(i))) != null) {
6566                            // We do have the package already installed under its
6567                            // original name...  should we use it?
6568                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6569                                // New package is not compatible with original.
6570                                origPackage = null;
6571                                continue;
6572                            } else if (origPackage.sharedUser != null) {
6573                                // Make sure uid is compatible between packages.
6574                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6575                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6576                                            + " to " + pkg.packageName + ": old uid "
6577                                            + origPackage.sharedUser.name
6578                                            + " differs from " + pkg.mSharedUserId);
6579                                    origPackage = null;
6580                                    continue;
6581                                }
6582                            } else {
6583                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6584                                        + pkg.packageName + " to old name " + origPackage.name);
6585                            }
6586                            break;
6587                        }
6588                    }
6589                }
6590            }
6591
6592            if (mTransferedPackages.contains(pkg.packageName)) {
6593                Slog.w(TAG, "Package " + pkg.packageName
6594                        + " was transferred to another, but its .apk remains");
6595            }
6596
6597            // Just create the setting, don't add it yet. For already existing packages
6598            // the PkgSetting exists already and doesn't have to be created.
6599            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6600                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6601                    pkg.applicationInfo.primaryCpuAbi,
6602                    pkg.applicationInfo.secondaryCpuAbi,
6603                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6604                    user, false);
6605            if (pkgSetting == null) {
6606                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6607                        "Creating application package " + pkg.packageName + " failed");
6608            }
6609
6610            if (pkgSetting.origPackage != null) {
6611                // If we are first transitioning from an original package,
6612                // fix up the new package's name now.  We need to do this after
6613                // looking up the package under its new name, so getPackageLP
6614                // can take care of fiddling things correctly.
6615                pkg.setPackageName(origPackage.name);
6616
6617                // File a report about this.
6618                String msg = "New package " + pkgSetting.realName
6619                        + " renamed to replace old package " + pkgSetting.name;
6620                reportSettingsProblem(Log.WARN, msg);
6621
6622                // Make a note of it.
6623                mTransferedPackages.add(origPackage.name);
6624
6625                // No longer need to retain this.
6626                pkgSetting.origPackage = null;
6627            }
6628
6629            if (realName != null) {
6630                // Make a note of it.
6631                mTransferedPackages.add(pkg.packageName);
6632            }
6633
6634            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6635                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6636            }
6637
6638            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6639                // Check all shared libraries and map to their actual file path.
6640                // We only do this here for apps not on a system dir, because those
6641                // are the only ones that can fail an install due to this.  We
6642                // will take care of the system apps by updating all of their
6643                // library paths after the scan is done.
6644                updateSharedLibrariesLPw(pkg, null);
6645            }
6646
6647            if (mFoundPolicyFile) {
6648                SELinuxMMAC.assignSeinfoValue(pkg);
6649            }
6650
6651            pkg.applicationInfo.uid = pkgSetting.appId;
6652            pkg.mExtras = pkgSetting;
6653            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6654                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6655                    // We just determined the app is signed correctly, so bring
6656                    // over the latest parsed certs.
6657                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6658                } else {
6659                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6660                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6661                                "Package " + pkg.packageName + " upgrade keys do not match the "
6662                                + "previously installed version");
6663                    } else {
6664                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6665                        String msg = "System package " + pkg.packageName
6666                            + " signature changed; retaining data.";
6667                        reportSettingsProblem(Log.WARN, msg);
6668                    }
6669                }
6670            } else {
6671                try {
6672                    verifySignaturesLP(pkgSetting, pkg);
6673                    // We just determined the app is signed correctly, so bring
6674                    // over the latest parsed certs.
6675                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6676                } catch (PackageManagerException e) {
6677                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6678                        throw e;
6679                    }
6680                    // The signature has changed, but this package is in the system
6681                    // image...  let's recover!
6682                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6683                    // However...  if this package is part of a shared user, but it
6684                    // doesn't match the signature of the shared user, let's fail.
6685                    // What this means is that you can't change the signatures
6686                    // associated with an overall shared user, which doesn't seem all
6687                    // that unreasonable.
6688                    if (pkgSetting.sharedUser != null) {
6689                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6690                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6691                            throw new PackageManagerException(
6692                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6693                                            "Signature mismatch for shared user : "
6694                                            + pkgSetting.sharedUser);
6695                        }
6696                    }
6697                    // File a report about this.
6698                    String msg = "System package " + pkg.packageName
6699                        + " signature changed; retaining data.";
6700                    reportSettingsProblem(Log.WARN, msg);
6701                }
6702            }
6703            // Verify that this new package doesn't have any content providers
6704            // that conflict with existing packages.  Only do this if the
6705            // package isn't already installed, since we don't want to break
6706            // things that are installed.
6707            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6708                final int N = pkg.providers.size();
6709                int i;
6710                for (i=0; i<N; i++) {
6711                    PackageParser.Provider p = pkg.providers.get(i);
6712                    if (p.info.authority != null) {
6713                        String names[] = p.info.authority.split(";");
6714                        for (int j = 0; j < names.length; j++) {
6715                            if (mProvidersByAuthority.containsKey(names[j])) {
6716                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6717                                final String otherPackageName =
6718                                        ((other != null && other.getComponentName() != null) ?
6719                                                other.getComponentName().getPackageName() : "?");
6720                                throw new PackageManagerException(
6721                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6722                                                "Can't install because provider name " + names[j]
6723                                                + " (in package " + pkg.applicationInfo.packageName
6724                                                + ") is already used by " + otherPackageName);
6725                            }
6726                        }
6727                    }
6728                }
6729            }
6730
6731            if (pkg.mAdoptPermissions != null) {
6732                // This package wants to adopt ownership of permissions from
6733                // another package.
6734                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6735                    final String origName = pkg.mAdoptPermissions.get(i);
6736                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6737                    if (orig != null) {
6738                        if (verifyPackageUpdateLPr(orig, pkg)) {
6739                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6740                                    + pkg.packageName);
6741                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6742                        }
6743                    }
6744                }
6745            }
6746        }
6747
6748        final String pkgName = pkg.packageName;
6749
6750        final long scanFileTime = scanFile.lastModified();
6751        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6752        pkg.applicationInfo.processName = fixProcessName(
6753                pkg.applicationInfo.packageName,
6754                pkg.applicationInfo.processName,
6755                pkg.applicationInfo.uid);
6756
6757        File dataPath;
6758        if (mPlatformPackage == pkg) {
6759            // The system package is special.
6760            dataPath = new File(Environment.getDataDirectory(), "system");
6761
6762            pkg.applicationInfo.dataDir = dataPath.getPath();
6763
6764        } else {
6765            // This is a normal package, need to make its data directory.
6766            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6767                    UserHandle.USER_OWNER, pkg.packageName);
6768
6769            boolean uidError = false;
6770            if (dataPath.exists()) {
6771                int currentUid = 0;
6772                try {
6773                    StructStat stat = Os.stat(dataPath.getPath());
6774                    currentUid = stat.st_uid;
6775                } catch (ErrnoException e) {
6776                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6777                }
6778
6779                // If we have mismatched owners for the data path, we have a problem.
6780                if (currentUid != pkg.applicationInfo.uid) {
6781                    boolean recovered = false;
6782                    if (currentUid == 0) {
6783                        // The directory somehow became owned by root.  Wow.
6784                        // This is probably because the system was stopped while
6785                        // installd was in the middle of messing with its libs
6786                        // directory.  Ask installd to fix that.
6787                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6788                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6789                        if (ret >= 0) {
6790                            recovered = true;
6791                            String msg = "Package " + pkg.packageName
6792                                    + " unexpectedly changed to uid 0; recovered to " +
6793                                    + pkg.applicationInfo.uid;
6794                            reportSettingsProblem(Log.WARN, msg);
6795                        }
6796                    }
6797                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6798                            || (scanFlags&SCAN_BOOTING) != 0)) {
6799                        // If this is a system app, we can at least delete its
6800                        // current data so the application will still work.
6801                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6802                        if (ret >= 0) {
6803                            // TODO: Kill the processes first
6804                            // Old data gone!
6805                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6806                                    ? "System package " : "Third party package ";
6807                            String msg = prefix + pkg.packageName
6808                                    + " has changed from uid: "
6809                                    + currentUid + " to "
6810                                    + pkg.applicationInfo.uid + "; old data erased";
6811                            reportSettingsProblem(Log.WARN, msg);
6812                            recovered = true;
6813
6814                            // And now re-install the app.
6815                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6816                                    pkg.applicationInfo.seinfo);
6817                            if (ret == -1) {
6818                                // Ack should not happen!
6819                                msg = prefix + pkg.packageName
6820                                        + " could not have data directory re-created after delete.";
6821                                reportSettingsProblem(Log.WARN, msg);
6822                                throw new PackageManagerException(
6823                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6824                            }
6825                        }
6826                        if (!recovered) {
6827                            mHasSystemUidErrors = true;
6828                        }
6829                    } else if (!recovered) {
6830                        // If we allow this install to proceed, we will be broken.
6831                        // Abort, abort!
6832                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6833                                "scanPackageLI");
6834                    }
6835                    if (!recovered) {
6836                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6837                            + pkg.applicationInfo.uid + "/fs_"
6838                            + currentUid;
6839                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6840                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6841                        String msg = "Package " + pkg.packageName
6842                                + " has mismatched uid: "
6843                                + currentUid + " on disk, "
6844                                + pkg.applicationInfo.uid + " in settings";
6845                        // writer
6846                        synchronized (mPackages) {
6847                            mSettings.mReadMessages.append(msg);
6848                            mSettings.mReadMessages.append('\n');
6849                            uidError = true;
6850                            if (!pkgSetting.uidError) {
6851                                reportSettingsProblem(Log.ERROR, msg);
6852                            }
6853                        }
6854                    }
6855                }
6856                pkg.applicationInfo.dataDir = dataPath.getPath();
6857                if (mShouldRestoreconData) {
6858                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6859                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6860                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6861                }
6862            } else {
6863                if (DEBUG_PACKAGE_SCANNING) {
6864                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6865                        Log.v(TAG, "Want this data dir: " + dataPath);
6866                }
6867                //invoke installer to do the actual installation
6868                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6869                        pkg.applicationInfo.seinfo);
6870                if (ret < 0) {
6871                    // Error from installer
6872                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6873                            "Unable to create data dirs [errorCode=" + ret + "]");
6874                }
6875
6876                if (dataPath.exists()) {
6877                    pkg.applicationInfo.dataDir = dataPath.getPath();
6878                } else {
6879                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6880                    pkg.applicationInfo.dataDir = null;
6881                }
6882            }
6883
6884            pkgSetting.uidError = uidError;
6885        }
6886
6887        final String path = scanFile.getPath();
6888        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6889
6890        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6891            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6892
6893            // Some system apps still use directory structure for native libraries
6894            // in which case we might end up not detecting abi solely based on apk
6895            // structure. Try to detect abi based on directory structure.
6896            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6897                    pkg.applicationInfo.primaryCpuAbi == null) {
6898                setBundledAppAbisAndRoots(pkg, pkgSetting);
6899                setNativeLibraryPaths(pkg);
6900            }
6901
6902        } else {
6903            if ((scanFlags & SCAN_MOVE) != 0) {
6904                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6905                // but we already have this packages package info in the PackageSetting. We just
6906                // use that and derive the native library path based on the new codepath.
6907                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6908                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6909            }
6910
6911            // Set native library paths again. For moves, the path will be updated based on the
6912            // ABIs we've determined above. For non-moves, the path will be updated based on the
6913            // ABIs we determined during compilation, but the path will depend on the final
6914            // package path (after the rename away from the stage path).
6915            setNativeLibraryPaths(pkg);
6916        }
6917
6918        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6919        final int[] userIds = sUserManager.getUserIds();
6920        synchronized (mInstallLock) {
6921            // Make sure all user data directories are ready to roll; we're okay
6922            // if they already exist
6923            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6924                for (int userId : userIds) {
6925                    if (userId != 0) {
6926                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6927                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6928                                pkg.applicationInfo.seinfo);
6929                    }
6930                }
6931            }
6932
6933            // Create a native library symlink only if we have native libraries
6934            // and if the native libraries are 32 bit libraries. We do not provide
6935            // this symlink for 64 bit libraries.
6936            if (pkg.applicationInfo.primaryCpuAbi != null &&
6937                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6938                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6939                for (int userId : userIds) {
6940                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6941                            nativeLibPath, userId) < 0) {
6942                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6943                                "Failed linking native library dir (user=" + userId + ")");
6944                    }
6945                }
6946            }
6947        }
6948
6949        // This is a special case for the "system" package, where the ABI is
6950        // dictated by the zygote configuration (and init.rc). We should keep track
6951        // of this ABI so that we can deal with "normal" applications that run under
6952        // the same UID correctly.
6953        if (mPlatformPackage == pkg) {
6954            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6955                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6956        }
6957
6958        // If there's a mismatch between the abi-override in the package setting
6959        // and the abiOverride specified for the install. Warn about this because we
6960        // would've already compiled the app without taking the package setting into
6961        // account.
6962        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6963            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6964                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6965                        " for package: " + pkg.packageName);
6966            }
6967        }
6968
6969        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6970        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6971        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6972
6973        // Copy the derived override back to the parsed package, so that we can
6974        // update the package settings accordingly.
6975        pkg.cpuAbiOverride = cpuAbiOverride;
6976
6977        if (DEBUG_ABI_SELECTION) {
6978            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6979                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6980                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6981        }
6982
6983        // Push the derived path down into PackageSettings so we know what to
6984        // clean up at uninstall time.
6985        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6986
6987        if (DEBUG_ABI_SELECTION) {
6988            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6989                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6990                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6991        }
6992
6993        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6994            // We don't do this here during boot because we can do it all
6995            // at once after scanning all existing packages.
6996            //
6997            // We also do this *before* we perform dexopt on this package, so that
6998            // we can avoid redundant dexopts, and also to make sure we've got the
6999            // code and package path correct.
7000            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7001                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7002        }
7003
7004        if ((scanFlags & SCAN_NO_DEX) == 0) {
7005            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7006                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7007            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7008                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7009            }
7010        }
7011        if (mFactoryTest && pkg.requestedPermissions.contains(
7012                android.Manifest.permission.FACTORY_TEST)) {
7013            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7014        }
7015
7016        ArrayList<PackageParser.Package> clientLibPkgs = null;
7017
7018        // writer
7019        synchronized (mPackages) {
7020            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7021                // Only system apps can add new shared libraries.
7022                if (pkg.libraryNames != null) {
7023                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7024                        String name = pkg.libraryNames.get(i);
7025                        boolean allowed = false;
7026                        if (pkg.isUpdatedSystemApp()) {
7027                            // New library entries can only be added through the
7028                            // system image.  This is important to get rid of a lot
7029                            // of nasty edge cases: for example if we allowed a non-
7030                            // system update of the app to add a library, then uninstalling
7031                            // the update would make the library go away, and assumptions
7032                            // we made such as through app install filtering would now
7033                            // have allowed apps on the device which aren't compatible
7034                            // with it.  Better to just have the restriction here, be
7035                            // conservative, and create many fewer cases that can negatively
7036                            // impact the user experience.
7037                            final PackageSetting sysPs = mSettings
7038                                    .getDisabledSystemPkgLPr(pkg.packageName);
7039                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7040                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7041                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7042                                        allowed = true;
7043                                        allowed = true;
7044                                        break;
7045                                    }
7046                                }
7047                            }
7048                        } else {
7049                            allowed = true;
7050                        }
7051                        if (allowed) {
7052                            if (!mSharedLibraries.containsKey(name)) {
7053                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7054                            } else if (!name.equals(pkg.packageName)) {
7055                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7056                                        + name + " already exists; skipping");
7057                            }
7058                        } else {
7059                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7060                                    + name + " that is not declared on system image; skipping");
7061                        }
7062                    }
7063                    if ((scanFlags&SCAN_BOOTING) == 0) {
7064                        // If we are not booting, we need to update any applications
7065                        // that are clients of our shared library.  If we are booting,
7066                        // this will all be done once the scan is complete.
7067                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7068                    }
7069                }
7070            }
7071        }
7072
7073        // We also need to dexopt any apps that are dependent on this library.  Note that
7074        // if these fail, we should abort the install since installing the library will
7075        // result in some apps being broken.
7076        if (clientLibPkgs != null) {
7077            if ((scanFlags & SCAN_NO_DEX) == 0) {
7078                for (int i = 0; i < clientLibPkgs.size(); i++) {
7079                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7080                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7081                            null /* instruction sets */, forceDex,
7082                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7083                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7084                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7085                                "scanPackageLI failed to dexopt clientLibPkgs");
7086                    }
7087                }
7088            }
7089        }
7090
7091        // Also need to kill any apps that are dependent on the library.
7092        if (clientLibPkgs != null) {
7093            for (int i=0; i<clientLibPkgs.size(); i++) {
7094                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7095                killApplication(clientPkg.applicationInfo.packageName,
7096                        clientPkg.applicationInfo.uid, "update lib");
7097            }
7098        }
7099
7100        // Make sure we're not adding any bogus keyset info
7101        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7102        ksms.assertScannedPackageValid(pkg);
7103
7104        // writer
7105        synchronized (mPackages) {
7106            // We don't expect installation to fail beyond this point
7107
7108            // Add the new setting to mSettings
7109            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7110            // Add the new setting to mPackages
7111            mPackages.put(pkg.applicationInfo.packageName, pkg);
7112            // Make sure we don't accidentally delete its data.
7113            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7114            while (iter.hasNext()) {
7115                PackageCleanItem item = iter.next();
7116                if (pkgName.equals(item.packageName)) {
7117                    iter.remove();
7118                }
7119            }
7120
7121            // Take care of first install / last update times.
7122            if (currentTime != 0) {
7123                if (pkgSetting.firstInstallTime == 0) {
7124                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7125                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7126                    pkgSetting.lastUpdateTime = currentTime;
7127                }
7128            } else if (pkgSetting.firstInstallTime == 0) {
7129                // We need *something*.  Take time time stamp of the file.
7130                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7131            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7132                if (scanFileTime != pkgSetting.timeStamp) {
7133                    // A package on the system image has changed; consider this
7134                    // to be an update.
7135                    pkgSetting.lastUpdateTime = scanFileTime;
7136                }
7137            }
7138
7139            // Add the package's KeySets to the global KeySetManagerService
7140            ksms.addScannedPackageLPw(pkg);
7141
7142            int N = pkg.providers.size();
7143            StringBuilder r = null;
7144            int i;
7145            for (i=0; i<N; i++) {
7146                PackageParser.Provider p = pkg.providers.get(i);
7147                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7148                        p.info.processName, pkg.applicationInfo.uid);
7149                mProviders.addProvider(p);
7150                p.syncable = p.info.isSyncable;
7151                if (p.info.authority != null) {
7152                    String names[] = p.info.authority.split(";");
7153                    p.info.authority = null;
7154                    for (int j = 0; j < names.length; j++) {
7155                        if (j == 1 && p.syncable) {
7156                            // We only want the first authority for a provider to possibly be
7157                            // syncable, so if we already added this provider using a different
7158                            // authority clear the syncable flag. We copy the provider before
7159                            // changing it because the mProviders object contains a reference
7160                            // to a provider that we don't want to change.
7161                            // Only do this for the second authority since the resulting provider
7162                            // object can be the same for all future authorities for this provider.
7163                            p = new PackageParser.Provider(p);
7164                            p.syncable = false;
7165                        }
7166                        if (!mProvidersByAuthority.containsKey(names[j])) {
7167                            mProvidersByAuthority.put(names[j], p);
7168                            if (p.info.authority == null) {
7169                                p.info.authority = names[j];
7170                            } else {
7171                                p.info.authority = p.info.authority + ";" + names[j];
7172                            }
7173                            if (DEBUG_PACKAGE_SCANNING) {
7174                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7175                                    Log.d(TAG, "Registered content provider: " + names[j]
7176                                            + ", className = " + p.info.name + ", isSyncable = "
7177                                            + p.info.isSyncable);
7178                            }
7179                        } else {
7180                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7181                            Slog.w(TAG, "Skipping provider name " + names[j] +
7182                                    " (in package " + pkg.applicationInfo.packageName +
7183                                    "): name already used by "
7184                                    + ((other != null && other.getComponentName() != null)
7185                                            ? other.getComponentName().getPackageName() : "?"));
7186                        }
7187                    }
7188                }
7189                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7190                    if (r == null) {
7191                        r = new StringBuilder(256);
7192                    } else {
7193                        r.append(' ');
7194                    }
7195                    r.append(p.info.name);
7196                }
7197            }
7198            if (r != null) {
7199                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7200            }
7201
7202            N = pkg.services.size();
7203            r = null;
7204            for (i=0; i<N; i++) {
7205                PackageParser.Service s = pkg.services.get(i);
7206                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7207                        s.info.processName, pkg.applicationInfo.uid);
7208                mServices.addService(s);
7209                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7210                    if (r == null) {
7211                        r = new StringBuilder(256);
7212                    } else {
7213                        r.append(' ');
7214                    }
7215                    r.append(s.info.name);
7216                }
7217            }
7218            if (r != null) {
7219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7220            }
7221
7222            N = pkg.receivers.size();
7223            r = null;
7224            for (i=0; i<N; i++) {
7225                PackageParser.Activity a = pkg.receivers.get(i);
7226                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7227                        a.info.processName, pkg.applicationInfo.uid);
7228                mReceivers.addActivity(a, "receiver");
7229                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7230                    if (r == null) {
7231                        r = new StringBuilder(256);
7232                    } else {
7233                        r.append(' ');
7234                    }
7235                    r.append(a.info.name);
7236                }
7237            }
7238            if (r != null) {
7239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7240            }
7241
7242            N = pkg.activities.size();
7243            r = null;
7244            for (i=0; i<N; i++) {
7245                PackageParser.Activity a = pkg.activities.get(i);
7246                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7247                        a.info.processName, pkg.applicationInfo.uid);
7248                mActivities.addActivity(a, "activity");
7249                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7250                    if (r == null) {
7251                        r = new StringBuilder(256);
7252                    } else {
7253                        r.append(' ');
7254                    }
7255                    r.append(a.info.name);
7256                }
7257            }
7258            if (r != null) {
7259                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7260            }
7261
7262            N = pkg.permissionGroups.size();
7263            r = null;
7264            for (i=0; i<N; i++) {
7265                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7266                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7267                if (cur == null) {
7268                    mPermissionGroups.put(pg.info.name, pg);
7269                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7270                        if (r == null) {
7271                            r = new StringBuilder(256);
7272                        } else {
7273                            r.append(' ');
7274                        }
7275                        r.append(pg.info.name);
7276                    }
7277                } else {
7278                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7279                            + pg.info.packageName + " ignored: original from "
7280                            + cur.info.packageName);
7281                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7282                        if (r == null) {
7283                            r = new StringBuilder(256);
7284                        } else {
7285                            r.append(' ');
7286                        }
7287                        r.append("DUP:");
7288                        r.append(pg.info.name);
7289                    }
7290                }
7291            }
7292            if (r != null) {
7293                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7294            }
7295
7296            N = pkg.permissions.size();
7297            r = null;
7298            for (i=0; i<N; i++) {
7299                PackageParser.Permission p = pkg.permissions.get(i);
7300
7301                // Now that permission groups have a special meaning, we ignore permission
7302                // groups for legacy apps to prevent unexpected behavior. In particular,
7303                // permissions for one app being granted to someone just becuase they happen
7304                // to be in a group defined by another app (before this had no implications).
7305                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7306                    p.group = mPermissionGroups.get(p.info.group);
7307                    // Warn for a permission in an unknown group.
7308                    if (p.info.group != null && p.group == null) {
7309                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7310                                + p.info.packageName + " in an unknown group " + p.info.group);
7311                    }
7312                }
7313
7314                ArrayMap<String, BasePermission> permissionMap =
7315                        p.tree ? mSettings.mPermissionTrees
7316                                : mSettings.mPermissions;
7317                BasePermission bp = permissionMap.get(p.info.name);
7318
7319                // Allow system apps to redefine non-system permissions
7320                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7321                    final boolean currentOwnerIsSystem = (bp.perm != null
7322                            && isSystemApp(bp.perm.owner));
7323                    if (isSystemApp(p.owner)) {
7324                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7325                            // It's a built-in permission and no owner, take ownership now
7326                            bp.packageSetting = pkgSetting;
7327                            bp.perm = p;
7328                            bp.uid = pkg.applicationInfo.uid;
7329                            bp.sourcePackage = p.info.packageName;
7330                        } else if (!currentOwnerIsSystem) {
7331                            String msg = "New decl " + p.owner + " of permission  "
7332                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7333                            reportSettingsProblem(Log.WARN, msg);
7334                            bp = null;
7335                        }
7336                    }
7337                }
7338
7339                if (bp == null) {
7340                    bp = new BasePermission(p.info.name, p.info.packageName,
7341                            BasePermission.TYPE_NORMAL);
7342                    permissionMap.put(p.info.name, bp);
7343                }
7344
7345                if (bp.perm == null) {
7346                    if (bp.sourcePackage == null
7347                            || bp.sourcePackage.equals(p.info.packageName)) {
7348                        BasePermission tree = findPermissionTreeLP(p.info.name);
7349                        if (tree == null
7350                                || tree.sourcePackage.equals(p.info.packageName)) {
7351                            bp.packageSetting = pkgSetting;
7352                            bp.perm = p;
7353                            bp.uid = pkg.applicationInfo.uid;
7354                            bp.sourcePackage = p.info.packageName;
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(p.info.name);
7362                            }
7363                        } else {
7364                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7365                                    + p.info.packageName + " ignored: base tree "
7366                                    + tree.name + " is from package "
7367                                    + tree.sourcePackage);
7368                        }
7369                    } else {
7370                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7371                                + p.info.packageName + " ignored: original from "
7372                                + bp.sourcePackage);
7373                    }
7374                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7375                    if (r == null) {
7376                        r = new StringBuilder(256);
7377                    } else {
7378                        r.append(' ');
7379                    }
7380                    r.append("DUP:");
7381                    r.append(p.info.name);
7382                }
7383                if (bp.perm == p) {
7384                    bp.protectionLevel = p.info.protectionLevel;
7385                }
7386            }
7387
7388            if (r != null) {
7389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7390            }
7391
7392            N = pkg.instrumentation.size();
7393            r = null;
7394            for (i=0; i<N; i++) {
7395                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7396                a.info.packageName = pkg.applicationInfo.packageName;
7397                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7398                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7399                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7400                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7401                a.info.dataDir = pkg.applicationInfo.dataDir;
7402
7403                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7404                // need other information about the application, like the ABI and what not ?
7405                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7406                mInstrumentation.put(a.getComponentName(), a);
7407                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7408                    if (r == null) {
7409                        r = new StringBuilder(256);
7410                    } else {
7411                        r.append(' ');
7412                    }
7413                    r.append(a.info.name);
7414                }
7415            }
7416            if (r != null) {
7417                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7418            }
7419
7420            if (pkg.protectedBroadcasts != null) {
7421                N = pkg.protectedBroadcasts.size();
7422                for (i=0; i<N; i++) {
7423                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7424                }
7425            }
7426
7427            pkgSetting.setTimeStamp(scanFileTime);
7428
7429            // Create idmap files for pairs of (packages, overlay packages).
7430            // Note: "android", ie framework-res.apk, is handled by native layers.
7431            if (pkg.mOverlayTarget != null) {
7432                // This is an overlay package.
7433                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7434                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7435                        mOverlays.put(pkg.mOverlayTarget,
7436                                new ArrayMap<String, PackageParser.Package>());
7437                    }
7438                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7439                    map.put(pkg.packageName, pkg);
7440                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7441                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7442                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7443                                "scanPackageLI failed to createIdmap");
7444                    }
7445                }
7446            } else if (mOverlays.containsKey(pkg.packageName) &&
7447                    !pkg.packageName.equals("android")) {
7448                // This is a regular package, with one or more known overlay packages.
7449                createIdmapsForPackageLI(pkg);
7450            }
7451        }
7452
7453        return pkg;
7454    }
7455
7456    /**
7457     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7458     * is derived purely on the basis of the contents of {@code scanFile} and
7459     * {@code cpuAbiOverride}.
7460     *
7461     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7462     */
7463    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7464                                 String cpuAbiOverride, boolean extractLibs)
7465            throws PackageManagerException {
7466        // TODO: We can probably be smarter about this stuff. For installed apps,
7467        // we can calculate this information at install time once and for all. For
7468        // system apps, we can probably assume that this information doesn't change
7469        // after the first boot scan. As things stand, we do lots of unnecessary work.
7470
7471        // Give ourselves some initial paths; we'll come back for another
7472        // pass once we've determined ABI below.
7473        setNativeLibraryPaths(pkg);
7474
7475        // We would never need to extract libs for forward-locked and external packages,
7476        // since the container service will do it for us. We shouldn't attempt to
7477        // extract libs from system app when it was not updated.
7478        if (pkg.isForwardLocked() || isExternal(pkg) ||
7479            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7480            extractLibs = false;
7481        }
7482
7483        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7484        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7485
7486        NativeLibraryHelper.Handle handle = null;
7487        try {
7488            handle = NativeLibraryHelper.Handle.create(scanFile);
7489            // TODO(multiArch): This can be null for apps that didn't go through the
7490            // usual installation process. We can calculate it again, like we
7491            // do during install time.
7492            //
7493            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7494            // unnecessary.
7495            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7496
7497            // Null out the abis so that they can be recalculated.
7498            pkg.applicationInfo.primaryCpuAbi = null;
7499            pkg.applicationInfo.secondaryCpuAbi = null;
7500            if (isMultiArch(pkg.applicationInfo)) {
7501                // Warn if we've set an abiOverride for multi-lib packages..
7502                // By definition, we need to copy both 32 and 64 bit libraries for
7503                // such packages.
7504                if (pkg.cpuAbiOverride != null
7505                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7506                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7507                }
7508
7509                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7510                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7511                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7512                    if (extractLibs) {
7513                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7514                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7515                                useIsaSpecificSubdirs);
7516                    } else {
7517                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7518                    }
7519                }
7520
7521                maybeThrowExceptionForMultiArchCopy(
7522                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7523
7524                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7525                    if (extractLibs) {
7526                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7527                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7528                                useIsaSpecificSubdirs);
7529                    } else {
7530                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7531                    }
7532                }
7533
7534                maybeThrowExceptionForMultiArchCopy(
7535                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7536
7537                if (abi64 >= 0) {
7538                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7539                }
7540
7541                if (abi32 >= 0) {
7542                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7543                    if (abi64 >= 0) {
7544                        pkg.applicationInfo.secondaryCpuAbi = abi;
7545                    } else {
7546                        pkg.applicationInfo.primaryCpuAbi = abi;
7547                    }
7548                }
7549            } else {
7550                String[] abiList = (cpuAbiOverride != null) ?
7551                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7552
7553                // Enable gross and lame hacks for apps that are built with old
7554                // SDK tools. We must scan their APKs for renderscript bitcode and
7555                // not launch them if it's present. Don't bother checking on devices
7556                // that don't have 64 bit support.
7557                boolean needsRenderScriptOverride = false;
7558                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7559                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7560                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7561                    needsRenderScriptOverride = true;
7562                }
7563
7564                final int copyRet;
7565                if (extractLibs) {
7566                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7567                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7568                } else {
7569                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7570                }
7571
7572                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7573                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7574                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7575                }
7576
7577                if (copyRet >= 0) {
7578                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7579                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7580                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7581                } else if (needsRenderScriptOverride) {
7582                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7583                }
7584            }
7585        } catch (IOException ioe) {
7586            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7587        } finally {
7588            IoUtils.closeQuietly(handle);
7589        }
7590
7591        // Now that we've calculated the ABIs and determined if it's an internal app,
7592        // we will go ahead and populate the nativeLibraryPath.
7593        setNativeLibraryPaths(pkg);
7594    }
7595
7596    /**
7597     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7598     * i.e, so that all packages can be run inside a single process if required.
7599     *
7600     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7601     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7602     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7603     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7604     * updating a package that belongs to a shared user.
7605     *
7606     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7607     * adds unnecessary complexity.
7608     */
7609    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7610            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7611        String requiredInstructionSet = null;
7612        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7613            requiredInstructionSet = VMRuntime.getInstructionSet(
7614                     scannedPackage.applicationInfo.primaryCpuAbi);
7615        }
7616
7617        PackageSetting requirer = null;
7618        for (PackageSetting ps : packagesForUser) {
7619            // If packagesForUser contains scannedPackage, we skip it. This will happen
7620            // when scannedPackage is an update of an existing package. Without this check,
7621            // we will never be able to change the ABI of any package belonging to a shared
7622            // user, even if it's compatible with other packages.
7623            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7624                if (ps.primaryCpuAbiString == null) {
7625                    continue;
7626                }
7627
7628                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7629                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7630                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7631                    // this but there's not much we can do.
7632                    String errorMessage = "Instruction set mismatch, "
7633                            + ((requirer == null) ? "[caller]" : requirer)
7634                            + " requires " + requiredInstructionSet + " whereas " + ps
7635                            + " requires " + instructionSet;
7636                    Slog.w(TAG, errorMessage);
7637                }
7638
7639                if (requiredInstructionSet == null) {
7640                    requiredInstructionSet = instructionSet;
7641                    requirer = ps;
7642                }
7643            }
7644        }
7645
7646        if (requiredInstructionSet != null) {
7647            String adjustedAbi;
7648            if (requirer != null) {
7649                // requirer != null implies that either scannedPackage was null or that scannedPackage
7650                // did not require an ABI, in which case we have to adjust scannedPackage to match
7651                // the ABI of the set (which is the same as requirer's ABI)
7652                adjustedAbi = requirer.primaryCpuAbiString;
7653                if (scannedPackage != null) {
7654                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7655                }
7656            } else {
7657                // requirer == null implies that we're updating all ABIs in the set to
7658                // match scannedPackage.
7659                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7660            }
7661
7662            for (PackageSetting ps : packagesForUser) {
7663                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7664                    if (ps.primaryCpuAbiString != null) {
7665                        continue;
7666                    }
7667
7668                    ps.primaryCpuAbiString = adjustedAbi;
7669                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7670                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7671                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7672
7673                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7674                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7675                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7676                            ps.primaryCpuAbiString = null;
7677                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7678                            return;
7679                        } else {
7680                            mInstaller.rmdex(ps.codePathString,
7681                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7682                        }
7683                    }
7684                }
7685            }
7686        }
7687    }
7688
7689    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7690        synchronized (mPackages) {
7691            mResolverReplaced = true;
7692            // Set up information for custom user intent resolution activity.
7693            mResolveActivity.applicationInfo = pkg.applicationInfo;
7694            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7695            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7696            mResolveActivity.processName = pkg.applicationInfo.packageName;
7697            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7698            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7699                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7700            mResolveActivity.theme = 0;
7701            mResolveActivity.exported = true;
7702            mResolveActivity.enabled = true;
7703            mResolveInfo.activityInfo = mResolveActivity;
7704            mResolveInfo.priority = 0;
7705            mResolveInfo.preferredOrder = 0;
7706            mResolveInfo.match = 0;
7707            mResolveComponentName = mCustomResolverComponentName;
7708            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7709                    mResolveComponentName);
7710        }
7711    }
7712
7713    private static String calculateBundledApkRoot(final String codePathString) {
7714        final File codePath = new File(codePathString);
7715        final File codeRoot;
7716        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7717            codeRoot = Environment.getRootDirectory();
7718        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7719            codeRoot = Environment.getOemDirectory();
7720        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7721            codeRoot = Environment.getVendorDirectory();
7722        } else {
7723            // Unrecognized code path; take its top real segment as the apk root:
7724            // e.g. /something/app/blah.apk => /something
7725            try {
7726                File f = codePath.getCanonicalFile();
7727                File parent = f.getParentFile();    // non-null because codePath is a file
7728                File tmp;
7729                while ((tmp = parent.getParentFile()) != null) {
7730                    f = parent;
7731                    parent = tmp;
7732                }
7733                codeRoot = f;
7734                Slog.w(TAG, "Unrecognized code path "
7735                        + codePath + " - using " + codeRoot);
7736            } catch (IOException e) {
7737                // Can't canonicalize the code path -- shenanigans?
7738                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7739                return Environment.getRootDirectory().getPath();
7740            }
7741        }
7742        return codeRoot.getPath();
7743    }
7744
7745    /**
7746     * Derive and set the location of native libraries for the given package,
7747     * which varies depending on where and how the package was installed.
7748     */
7749    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7750        final ApplicationInfo info = pkg.applicationInfo;
7751        final String codePath = pkg.codePath;
7752        final File codeFile = new File(codePath);
7753        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7754        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7755
7756        info.nativeLibraryRootDir = null;
7757        info.nativeLibraryRootRequiresIsa = false;
7758        info.nativeLibraryDir = null;
7759        info.secondaryNativeLibraryDir = null;
7760
7761        if (isApkFile(codeFile)) {
7762            // Monolithic install
7763            if (bundledApp) {
7764                // If "/system/lib64/apkname" exists, assume that is the per-package
7765                // native library directory to use; otherwise use "/system/lib/apkname".
7766                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7767                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7768                        getPrimaryInstructionSet(info));
7769
7770                // This is a bundled system app so choose the path based on the ABI.
7771                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7772                // is just the default path.
7773                final String apkName = deriveCodePathName(codePath);
7774                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7775                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7776                        apkName).getAbsolutePath();
7777
7778                if (info.secondaryCpuAbi != null) {
7779                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7780                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7781                            secondaryLibDir, apkName).getAbsolutePath();
7782                }
7783            } else if (asecApp) {
7784                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7785                        .getAbsolutePath();
7786            } else {
7787                final String apkName = deriveCodePathName(codePath);
7788                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7789                        .getAbsolutePath();
7790            }
7791
7792            info.nativeLibraryRootRequiresIsa = false;
7793            info.nativeLibraryDir = info.nativeLibraryRootDir;
7794        } else {
7795            // Cluster install
7796            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7797            info.nativeLibraryRootRequiresIsa = true;
7798
7799            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7800                    getPrimaryInstructionSet(info)).getAbsolutePath();
7801
7802            if (info.secondaryCpuAbi != null) {
7803                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7804                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7805            }
7806        }
7807    }
7808
7809    /**
7810     * Calculate the abis and roots for a bundled app. These can uniquely
7811     * be determined from the contents of the system partition, i.e whether
7812     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7813     * of this information, and instead assume that the system was built
7814     * sensibly.
7815     */
7816    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7817                                           PackageSetting pkgSetting) {
7818        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7819
7820        // If "/system/lib64/apkname" exists, assume that is the per-package
7821        // native library directory to use; otherwise use "/system/lib/apkname".
7822        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7823        setBundledAppAbi(pkg, apkRoot, apkName);
7824        // pkgSetting might be null during rescan following uninstall of updates
7825        // to a bundled app, so accommodate that possibility.  The settings in
7826        // that case will be established later from the parsed package.
7827        //
7828        // If the settings aren't null, sync them up with what we've just derived.
7829        // note that apkRoot isn't stored in the package settings.
7830        if (pkgSetting != null) {
7831            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7832            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7833        }
7834    }
7835
7836    /**
7837     * Deduces the ABI of a bundled app and sets the relevant fields on the
7838     * parsed pkg object.
7839     *
7840     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7841     *        under which system libraries are installed.
7842     * @param apkName the name of the installed package.
7843     */
7844    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7845        final File codeFile = new File(pkg.codePath);
7846
7847        final boolean has64BitLibs;
7848        final boolean has32BitLibs;
7849        if (isApkFile(codeFile)) {
7850            // Monolithic install
7851            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7852            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7853        } else {
7854            // Cluster install
7855            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7856            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7857                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7858                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7859                has64BitLibs = (new File(rootDir, isa)).exists();
7860            } else {
7861                has64BitLibs = false;
7862            }
7863            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7864                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7865                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7866                has32BitLibs = (new File(rootDir, isa)).exists();
7867            } else {
7868                has32BitLibs = false;
7869            }
7870        }
7871
7872        if (has64BitLibs && !has32BitLibs) {
7873            // The package has 64 bit libs, but not 32 bit libs. Its primary
7874            // ABI should be 64 bit. We can safely assume here that the bundled
7875            // native libraries correspond to the most preferred ABI in the list.
7876
7877            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7878            pkg.applicationInfo.secondaryCpuAbi = null;
7879        } else if (has32BitLibs && !has64BitLibs) {
7880            // The package has 32 bit libs but not 64 bit libs. Its primary
7881            // ABI should be 32 bit.
7882
7883            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7884            pkg.applicationInfo.secondaryCpuAbi = null;
7885        } else if (has32BitLibs && has64BitLibs) {
7886            // The application has both 64 and 32 bit bundled libraries. We check
7887            // here that the app declares multiArch support, and warn if it doesn't.
7888            //
7889            // We will be lenient here and record both ABIs. The primary will be the
7890            // ABI that's higher on the list, i.e, a device that's configured to prefer
7891            // 64 bit apps will see a 64 bit primary ABI,
7892
7893            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7894                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7895            }
7896
7897            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7898                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7899                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7900            } else {
7901                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7902                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7903            }
7904        } else {
7905            pkg.applicationInfo.primaryCpuAbi = null;
7906            pkg.applicationInfo.secondaryCpuAbi = null;
7907        }
7908    }
7909
7910    private void killApplication(String pkgName, int appId, String reason) {
7911        // Request the ActivityManager to kill the process(only for existing packages)
7912        // so that we do not end up in a confused state while the user is still using the older
7913        // version of the application while the new one gets installed.
7914        IActivityManager am = ActivityManagerNative.getDefault();
7915        if (am != null) {
7916            try {
7917                am.killApplicationWithAppId(pkgName, appId, reason);
7918            } catch (RemoteException e) {
7919            }
7920        }
7921    }
7922
7923    void removePackageLI(PackageSetting ps, boolean chatty) {
7924        if (DEBUG_INSTALL) {
7925            if (chatty)
7926                Log.d(TAG, "Removing package " + ps.name);
7927        }
7928
7929        // writer
7930        synchronized (mPackages) {
7931            mPackages.remove(ps.name);
7932            final PackageParser.Package pkg = ps.pkg;
7933            if (pkg != null) {
7934                cleanPackageDataStructuresLILPw(pkg, chatty);
7935            }
7936        }
7937    }
7938
7939    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7940        if (DEBUG_INSTALL) {
7941            if (chatty)
7942                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7943        }
7944
7945        // writer
7946        synchronized (mPackages) {
7947            mPackages.remove(pkg.applicationInfo.packageName);
7948            cleanPackageDataStructuresLILPw(pkg, chatty);
7949        }
7950    }
7951
7952    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7953        int N = pkg.providers.size();
7954        StringBuilder r = null;
7955        int i;
7956        for (i=0; i<N; i++) {
7957            PackageParser.Provider p = pkg.providers.get(i);
7958            mProviders.removeProvider(p);
7959            if (p.info.authority == null) {
7960
7961                /* There was another ContentProvider with this authority when
7962                 * this app was installed so this authority is null,
7963                 * Ignore it as we don't have to unregister the provider.
7964                 */
7965                continue;
7966            }
7967            String names[] = p.info.authority.split(";");
7968            for (int j = 0; j < names.length; j++) {
7969                if (mProvidersByAuthority.get(names[j]) == p) {
7970                    mProvidersByAuthority.remove(names[j]);
7971                    if (DEBUG_REMOVE) {
7972                        if (chatty)
7973                            Log.d(TAG, "Unregistered content provider: " + names[j]
7974                                    + ", className = " + p.info.name + ", isSyncable = "
7975                                    + p.info.isSyncable);
7976                    }
7977                }
7978            }
7979            if (DEBUG_REMOVE && chatty) {
7980                if (r == null) {
7981                    r = new StringBuilder(256);
7982                } else {
7983                    r.append(' ');
7984                }
7985                r.append(p.info.name);
7986            }
7987        }
7988        if (r != null) {
7989            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7990        }
7991
7992        N = pkg.services.size();
7993        r = null;
7994        for (i=0; i<N; i++) {
7995            PackageParser.Service s = pkg.services.get(i);
7996            mServices.removeService(s);
7997            if (chatty) {
7998                if (r == null) {
7999                    r = new StringBuilder(256);
8000                } else {
8001                    r.append(' ');
8002                }
8003                r.append(s.info.name);
8004            }
8005        }
8006        if (r != null) {
8007            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8008        }
8009
8010        N = pkg.receivers.size();
8011        r = null;
8012        for (i=0; i<N; i++) {
8013            PackageParser.Activity a = pkg.receivers.get(i);
8014            mReceivers.removeActivity(a, "receiver");
8015            if (DEBUG_REMOVE && chatty) {
8016                if (r == null) {
8017                    r = new StringBuilder(256);
8018                } else {
8019                    r.append(' ');
8020                }
8021                r.append(a.info.name);
8022            }
8023        }
8024        if (r != null) {
8025            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8026        }
8027
8028        N = pkg.activities.size();
8029        r = null;
8030        for (i=0; i<N; i++) {
8031            PackageParser.Activity a = pkg.activities.get(i);
8032            mActivities.removeActivity(a, "activity");
8033            if (DEBUG_REMOVE && chatty) {
8034                if (r == null) {
8035                    r = new StringBuilder(256);
8036                } else {
8037                    r.append(' ');
8038                }
8039                r.append(a.info.name);
8040            }
8041        }
8042        if (r != null) {
8043            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8044        }
8045
8046        N = pkg.permissions.size();
8047        r = null;
8048        for (i=0; i<N; i++) {
8049            PackageParser.Permission p = pkg.permissions.get(i);
8050            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8051            if (bp == null) {
8052                bp = mSettings.mPermissionTrees.get(p.info.name);
8053            }
8054            if (bp != null && bp.perm == p) {
8055                bp.perm = null;
8056                if (DEBUG_REMOVE && chatty) {
8057                    if (r == null) {
8058                        r = new StringBuilder(256);
8059                    } else {
8060                        r.append(' ');
8061                    }
8062                    r.append(p.info.name);
8063                }
8064            }
8065            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8066                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8067                if (appOpPerms != null) {
8068                    appOpPerms.remove(pkg.packageName);
8069                }
8070            }
8071        }
8072        if (r != null) {
8073            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8074        }
8075
8076        N = pkg.requestedPermissions.size();
8077        r = null;
8078        for (i=0; i<N; i++) {
8079            String perm = pkg.requestedPermissions.get(i);
8080            BasePermission bp = mSettings.mPermissions.get(perm);
8081            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8082                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8083                if (appOpPerms != null) {
8084                    appOpPerms.remove(pkg.packageName);
8085                    if (appOpPerms.isEmpty()) {
8086                        mAppOpPermissionPackages.remove(perm);
8087                    }
8088                }
8089            }
8090        }
8091        if (r != null) {
8092            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8093        }
8094
8095        N = pkg.instrumentation.size();
8096        r = null;
8097        for (i=0; i<N; i++) {
8098            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8099            mInstrumentation.remove(a.getComponentName());
8100            if (DEBUG_REMOVE && chatty) {
8101                if (r == null) {
8102                    r = new StringBuilder(256);
8103                } else {
8104                    r.append(' ');
8105                }
8106                r.append(a.info.name);
8107            }
8108        }
8109        if (r != null) {
8110            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8111        }
8112
8113        r = null;
8114        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8115            // Only system apps can hold shared libraries.
8116            if (pkg.libraryNames != null) {
8117                for (i=0; i<pkg.libraryNames.size(); i++) {
8118                    String name = pkg.libraryNames.get(i);
8119                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8120                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8121                        mSharedLibraries.remove(name);
8122                        if (DEBUG_REMOVE && chatty) {
8123                            if (r == null) {
8124                                r = new StringBuilder(256);
8125                            } else {
8126                                r.append(' ');
8127                            }
8128                            r.append(name);
8129                        }
8130                    }
8131                }
8132            }
8133        }
8134        if (r != null) {
8135            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8136        }
8137    }
8138
8139    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8140        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8141            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8142                return true;
8143            }
8144        }
8145        return false;
8146    }
8147
8148    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8149    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8150    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8151
8152    private void updatePermissionsLPw(String changingPkg,
8153            PackageParser.Package pkgInfo, int flags) {
8154        // Make sure there are no dangling permission trees.
8155        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8156        while (it.hasNext()) {
8157            final BasePermission bp = it.next();
8158            if (bp.packageSetting == null) {
8159                // We may not yet have parsed the package, so just see if
8160                // we still know about its settings.
8161                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8162            }
8163            if (bp.packageSetting == null) {
8164                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8165                        + " from package " + bp.sourcePackage);
8166                it.remove();
8167            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8168                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8169                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8170                            + " from package " + bp.sourcePackage);
8171                    flags |= UPDATE_PERMISSIONS_ALL;
8172                    it.remove();
8173                }
8174            }
8175        }
8176
8177        // Make sure all dynamic permissions have been assigned to a package,
8178        // and make sure there are no dangling permissions.
8179        it = mSettings.mPermissions.values().iterator();
8180        while (it.hasNext()) {
8181            final BasePermission bp = it.next();
8182            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8183                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8184                        + bp.name + " pkg=" + bp.sourcePackage
8185                        + " info=" + bp.pendingInfo);
8186                if (bp.packageSetting == null && bp.pendingInfo != null) {
8187                    final BasePermission tree = findPermissionTreeLP(bp.name);
8188                    if (tree != null && tree.perm != null) {
8189                        bp.packageSetting = tree.packageSetting;
8190                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8191                                new PermissionInfo(bp.pendingInfo));
8192                        bp.perm.info.packageName = tree.perm.info.packageName;
8193                        bp.perm.info.name = bp.name;
8194                        bp.uid = tree.uid;
8195                    }
8196                }
8197            }
8198            if (bp.packageSetting == null) {
8199                // We may not yet have parsed the package, so just see if
8200                // we still know about its settings.
8201                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8202            }
8203            if (bp.packageSetting == null) {
8204                Slog.w(TAG, "Removing dangling permission: " + bp.name
8205                        + " from package " + bp.sourcePackage);
8206                it.remove();
8207            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8208                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8209                    Slog.i(TAG, "Removing old permission: " + bp.name
8210                            + " from package " + bp.sourcePackage);
8211                    flags |= UPDATE_PERMISSIONS_ALL;
8212                    it.remove();
8213                }
8214            }
8215        }
8216
8217        // Now update the permissions for all packages, in particular
8218        // replace the granted permissions of the system packages.
8219        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8220            for (PackageParser.Package pkg : mPackages.values()) {
8221                if (pkg != pkgInfo) {
8222                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8223                            changingPkg);
8224                }
8225            }
8226        }
8227
8228        if (pkgInfo != null) {
8229            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8230        }
8231    }
8232
8233    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8234            String packageOfInterest) {
8235        // IMPORTANT: There are two types of permissions: install and runtime.
8236        // Install time permissions are granted when the app is installed to
8237        // all device users and users added in the future. Runtime permissions
8238        // are granted at runtime explicitly to specific users. Normal and signature
8239        // protected permissions are install time permissions. Dangerous permissions
8240        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8241        // otherwise they are runtime permissions. This function does not manage
8242        // runtime permissions except for the case an app targeting Lollipop MR1
8243        // being upgraded to target a newer SDK, in which case dangerous permissions
8244        // are transformed from install time to runtime ones.
8245
8246        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8247        if (ps == null) {
8248            return;
8249        }
8250
8251        PermissionsState permissionsState = ps.getPermissionsState();
8252        PermissionsState origPermissions = permissionsState;
8253
8254        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8255
8256        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8257
8258        boolean changedInstallPermission = false;
8259
8260        if (replace) {
8261            ps.installPermissionsFixed = false;
8262            if (!ps.isSharedUser()) {
8263                origPermissions = new PermissionsState(permissionsState);
8264                permissionsState.reset();
8265            }
8266        }
8267
8268        permissionsState.setGlobalGids(mGlobalGids);
8269
8270        final int N = pkg.requestedPermissions.size();
8271        for (int i=0; i<N; i++) {
8272            final String name = pkg.requestedPermissions.get(i);
8273            final BasePermission bp = mSettings.mPermissions.get(name);
8274
8275            if (DEBUG_INSTALL) {
8276                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8277            }
8278
8279            if (bp == null || bp.packageSetting == null) {
8280                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8281                    Slog.w(TAG, "Unknown permission " + name
8282                            + " in package " + pkg.packageName);
8283                }
8284                continue;
8285            }
8286
8287            final String perm = bp.name;
8288            boolean allowedSig = false;
8289            int grant = GRANT_DENIED;
8290
8291            // Keep track of app op permissions.
8292            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8293                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8294                if (pkgs == null) {
8295                    pkgs = new ArraySet<>();
8296                    mAppOpPermissionPackages.put(bp.name, pkgs);
8297                }
8298                pkgs.add(pkg.packageName);
8299            }
8300
8301            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8302            switch (level) {
8303                case PermissionInfo.PROTECTION_NORMAL: {
8304                    // For all apps normal permissions are install time ones.
8305                    grant = GRANT_INSTALL;
8306                } break;
8307
8308                case PermissionInfo.PROTECTION_DANGEROUS: {
8309                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8310                        // For legacy apps dangerous permissions are install time ones.
8311                        grant = GRANT_INSTALL_LEGACY;
8312                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8313                        // For legacy apps that became modern, install becomes runtime.
8314                        grant = GRANT_UPGRADE;
8315                    } else {
8316                        // For modern apps keep runtime permissions unchanged.
8317                        grant = GRANT_RUNTIME;
8318                    }
8319                } break;
8320
8321                case PermissionInfo.PROTECTION_SIGNATURE: {
8322                    // For all apps signature permissions are install time ones.
8323                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8324                    if (allowedSig) {
8325                        grant = GRANT_INSTALL;
8326                    }
8327                } break;
8328            }
8329
8330            if (DEBUG_INSTALL) {
8331                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8332            }
8333
8334            if (grant != GRANT_DENIED) {
8335                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8336                    // If this is an existing, non-system package, then
8337                    // we can't add any new permissions to it.
8338                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8339                        // Except...  if this is a permission that was added
8340                        // to the platform (note: need to only do this when
8341                        // updating the platform).
8342                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8343                            grant = GRANT_DENIED;
8344                        }
8345                    }
8346                }
8347
8348                switch (grant) {
8349                    case GRANT_INSTALL: {
8350                        // Revoke this as runtime permission to handle the case of
8351                        // a runtime permission being downgraded to an install one.
8352                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8353                            if (origPermissions.getRuntimePermissionState(
8354                                    bp.name, userId) != null) {
8355                                // Revoke the runtime permission and clear the flags.
8356                                origPermissions.revokeRuntimePermission(bp, userId);
8357                                origPermissions.updatePermissionFlags(bp, userId,
8358                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8359                                // If we revoked a permission permission, we have to write.
8360                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8361                                        changedRuntimePermissionUserIds, userId);
8362                            }
8363                        }
8364                        // Grant an install permission.
8365                        if (permissionsState.grantInstallPermission(bp) !=
8366                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8367                            changedInstallPermission = true;
8368                        }
8369                    } break;
8370
8371                    case GRANT_INSTALL_LEGACY: {
8372                        // Grant an install permission.
8373                        if (permissionsState.grantInstallPermission(bp) !=
8374                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8375                            changedInstallPermission = true;
8376                        }
8377                    } break;
8378
8379                    case GRANT_RUNTIME: {
8380                        // Grant previously granted runtime permissions.
8381                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8382                            PermissionState permissionState = origPermissions
8383                                    .getRuntimePermissionState(bp.name, userId);
8384                            final int flags = permissionState != null
8385                                    ? permissionState.getFlags() : 0;
8386                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8387                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8388                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8389                                    // If we cannot put the permission as it was, we have to write.
8390                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8391                                            changedRuntimePermissionUserIds, userId);
8392                                }
8393                            }
8394                            // Propagate the permission flags.
8395                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8396                        }
8397                    } break;
8398
8399                    case GRANT_UPGRADE: {
8400                        // Grant runtime permissions for a previously held install permission.
8401                        PermissionState permissionState = origPermissions
8402                                .getInstallPermissionState(bp.name);
8403                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8404
8405                        if (origPermissions.revokeInstallPermission(bp)
8406                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8407                            // We will be transferring the permission flags, so clear them.
8408                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8409                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8410                            changedInstallPermission = true;
8411                        }
8412
8413                        // If the permission is not to be promoted to runtime we ignore it and
8414                        // also its other flags as they are not applicable to install permissions.
8415                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8416                            for (int userId : currentUserIds) {
8417                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8418                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8419                                    // Transfer the permission flags.
8420                                    permissionsState.updatePermissionFlags(bp, userId,
8421                                            flags, flags);
8422                                    // If we granted the permission, we have to write.
8423                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8424                                            changedRuntimePermissionUserIds, userId);
8425                                }
8426                            }
8427                        }
8428                    } break;
8429
8430                    default: {
8431                        if (packageOfInterest == null
8432                                || packageOfInterest.equals(pkg.packageName)) {
8433                            Slog.w(TAG, "Not granting permission " + perm
8434                                    + " to package " + pkg.packageName
8435                                    + " because it was previously installed without");
8436                        }
8437                    } break;
8438                }
8439            } else {
8440                if (permissionsState.revokeInstallPermission(bp) !=
8441                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8442                    // Also drop the permission flags.
8443                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8444                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8445                    changedInstallPermission = true;
8446                    Slog.i(TAG, "Un-granting permission " + perm
8447                            + " from package " + pkg.packageName
8448                            + " (protectionLevel=" + bp.protectionLevel
8449                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8450                            + ")");
8451                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8452                    // Don't print warning for app op permissions, since it is fine for them
8453                    // not to be granted, there is a UI for the user to decide.
8454                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8455                        Slog.w(TAG, "Not granting permission " + perm
8456                                + " to package " + pkg.packageName
8457                                + " (protectionLevel=" + bp.protectionLevel
8458                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8459                                + ")");
8460                    }
8461                }
8462            }
8463        }
8464
8465        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8466                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8467            // This is the first that we have heard about this package, so the
8468            // permissions we have now selected are fixed until explicitly
8469            // changed.
8470            ps.installPermissionsFixed = true;
8471        }
8472
8473        // Persist the runtime permissions state for users with changes.
8474        for (int userId : changedRuntimePermissionUserIds) {
8475            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8476        }
8477    }
8478
8479    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8480        boolean allowed = false;
8481        final int NP = PackageParser.NEW_PERMISSIONS.length;
8482        for (int ip=0; ip<NP; ip++) {
8483            final PackageParser.NewPermissionInfo npi
8484                    = PackageParser.NEW_PERMISSIONS[ip];
8485            if (npi.name.equals(perm)
8486                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8487                allowed = true;
8488                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8489                        + pkg.packageName);
8490                break;
8491            }
8492        }
8493        return allowed;
8494    }
8495
8496    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8497            BasePermission bp, PermissionsState origPermissions) {
8498        boolean allowed;
8499        allowed = (compareSignatures(
8500                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8501                        == PackageManager.SIGNATURE_MATCH)
8502                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8503                        == PackageManager.SIGNATURE_MATCH);
8504        if (!allowed && (bp.protectionLevel
8505                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8506            if (isSystemApp(pkg)) {
8507                // For updated system applications, a system permission
8508                // is granted only if it had been defined by the original application.
8509                if (pkg.isUpdatedSystemApp()) {
8510                    final PackageSetting sysPs = mSettings
8511                            .getDisabledSystemPkgLPr(pkg.packageName);
8512                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8513                        // If the original was granted this permission, we take
8514                        // that grant decision as read and propagate it to the
8515                        // update.
8516                        if (sysPs.isPrivileged()) {
8517                            allowed = true;
8518                        }
8519                    } else {
8520                        // The system apk may have been updated with an older
8521                        // version of the one on the data partition, but which
8522                        // granted a new system permission that it didn't have
8523                        // before.  In this case we do want to allow the app to
8524                        // now get the new permission if the ancestral apk is
8525                        // privileged to get it.
8526                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8527                            for (int j=0;
8528                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8529                                if (perm.equals(
8530                                        sysPs.pkg.requestedPermissions.get(j))) {
8531                                    allowed = true;
8532                                    break;
8533                                }
8534                            }
8535                        }
8536                    }
8537                } else {
8538                    allowed = isPrivilegedApp(pkg);
8539                }
8540            }
8541        }
8542        if (!allowed) {
8543            if (!allowed && (bp.protectionLevel
8544                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8545                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8546                // If this was a previously normal/dangerous permission that got moved
8547                // to a system permission as part of the runtime permission redesign, then
8548                // we still want to blindly grant it to old apps.
8549                allowed = true;
8550            }
8551            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8552                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8553                // If this permission is to be granted to the system installer and
8554                // this app is an installer, then it gets the permission.
8555                allowed = true;
8556            }
8557            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8558                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8559                // If this permission is to be granted to the system verifier and
8560                // this app is a verifier, then it gets the permission.
8561                allowed = true;
8562            }
8563            if (!allowed && (bp.protectionLevel
8564                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8565                    && isSystemApp(pkg)) {
8566                // Any pre-installed system app is allowed to get this permission.
8567                allowed = true;
8568            }
8569            if (!allowed && (bp.protectionLevel
8570                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8571                // For development permissions, a development permission
8572                // is granted only if it was already granted.
8573                allowed = origPermissions.hasInstallPermission(perm);
8574            }
8575        }
8576        return allowed;
8577    }
8578
8579    final class ActivityIntentResolver
8580            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8581        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8582                boolean defaultOnly, int userId) {
8583            if (!sUserManager.exists(userId)) return null;
8584            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8585            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8586        }
8587
8588        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8589                int userId) {
8590            if (!sUserManager.exists(userId)) return null;
8591            mFlags = flags;
8592            return super.queryIntent(intent, resolvedType,
8593                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8594        }
8595
8596        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8597                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8598            if (!sUserManager.exists(userId)) return null;
8599            if (packageActivities == null) {
8600                return null;
8601            }
8602            mFlags = flags;
8603            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8604            final int N = packageActivities.size();
8605            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8606                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8607
8608            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8609            for (int i = 0; i < N; ++i) {
8610                intentFilters = packageActivities.get(i).intents;
8611                if (intentFilters != null && intentFilters.size() > 0) {
8612                    PackageParser.ActivityIntentInfo[] array =
8613                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8614                    intentFilters.toArray(array);
8615                    listCut.add(array);
8616                }
8617            }
8618            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8619        }
8620
8621        public final void addActivity(PackageParser.Activity a, String type) {
8622            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8623            mActivities.put(a.getComponentName(), a);
8624            if (DEBUG_SHOW_INFO)
8625                Log.v(
8626                TAG, "  " + type + " " +
8627                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8628            if (DEBUG_SHOW_INFO)
8629                Log.v(TAG, "    Class=" + a.info.name);
8630            final int NI = a.intents.size();
8631            for (int j=0; j<NI; j++) {
8632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8633                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8634                    intent.setPriority(0);
8635                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8636                            + a.className + " with priority > 0, forcing to 0");
8637                }
8638                if (DEBUG_SHOW_INFO) {
8639                    Log.v(TAG, "    IntentFilter:");
8640                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8641                }
8642                if (!intent.debugCheck()) {
8643                    Log.w(TAG, "==> For Activity " + a.info.name);
8644                }
8645                addFilter(intent);
8646            }
8647        }
8648
8649        public final void removeActivity(PackageParser.Activity a, String type) {
8650            mActivities.remove(a.getComponentName());
8651            if (DEBUG_SHOW_INFO) {
8652                Log.v(TAG, "  " + type + " "
8653                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8654                                : a.info.name) + ":");
8655                Log.v(TAG, "    Class=" + a.info.name);
8656            }
8657            final int NI = a.intents.size();
8658            for (int j=0; j<NI; j++) {
8659                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8660                if (DEBUG_SHOW_INFO) {
8661                    Log.v(TAG, "    IntentFilter:");
8662                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8663                }
8664                removeFilter(intent);
8665            }
8666        }
8667
8668        @Override
8669        protected boolean allowFilterResult(
8670                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8671            ActivityInfo filterAi = filter.activity.info;
8672            for (int i=dest.size()-1; i>=0; i--) {
8673                ActivityInfo destAi = dest.get(i).activityInfo;
8674                if (destAi.name == filterAi.name
8675                        && destAi.packageName == filterAi.packageName) {
8676                    return false;
8677                }
8678            }
8679            return true;
8680        }
8681
8682        @Override
8683        protected ActivityIntentInfo[] newArray(int size) {
8684            return new ActivityIntentInfo[size];
8685        }
8686
8687        @Override
8688        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8689            if (!sUserManager.exists(userId)) return true;
8690            PackageParser.Package p = filter.activity.owner;
8691            if (p != null) {
8692                PackageSetting ps = (PackageSetting)p.mExtras;
8693                if (ps != null) {
8694                    // System apps are never considered stopped for purposes of
8695                    // filtering, because there may be no way for the user to
8696                    // actually re-launch them.
8697                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8698                            && ps.getStopped(userId);
8699                }
8700            }
8701            return false;
8702        }
8703
8704        @Override
8705        protected boolean isPackageForFilter(String packageName,
8706                PackageParser.ActivityIntentInfo info) {
8707            return packageName.equals(info.activity.owner.packageName);
8708        }
8709
8710        @Override
8711        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8712                int match, int userId) {
8713            if (!sUserManager.exists(userId)) return null;
8714            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8715                return null;
8716            }
8717            final PackageParser.Activity activity = info.activity;
8718            if (mSafeMode && (activity.info.applicationInfo.flags
8719                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8720                return null;
8721            }
8722            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8723            if (ps == null) {
8724                return null;
8725            }
8726            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8727                    ps.readUserState(userId), userId);
8728            if (ai == null) {
8729                return null;
8730            }
8731            final ResolveInfo res = new ResolveInfo();
8732            res.activityInfo = ai;
8733            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8734                res.filter = info;
8735            }
8736            if (info != null) {
8737                res.handleAllWebDataURI = info.handleAllWebDataURI();
8738            }
8739            res.priority = info.getPriority();
8740            res.preferredOrder = activity.owner.mPreferredOrder;
8741            //System.out.println("Result: " + res.activityInfo.className +
8742            //                   " = " + res.priority);
8743            res.match = match;
8744            res.isDefault = info.hasDefault;
8745            res.labelRes = info.labelRes;
8746            res.nonLocalizedLabel = info.nonLocalizedLabel;
8747            if (userNeedsBadging(userId)) {
8748                res.noResourceId = true;
8749            } else {
8750                res.icon = info.icon;
8751            }
8752            res.iconResourceId = info.icon;
8753            res.system = res.activityInfo.applicationInfo.isSystemApp();
8754            return res;
8755        }
8756
8757        @Override
8758        protected void sortResults(List<ResolveInfo> results) {
8759            Collections.sort(results, mResolvePrioritySorter);
8760        }
8761
8762        @Override
8763        protected void dumpFilter(PrintWriter out, String prefix,
8764                PackageParser.ActivityIntentInfo filter) {
8765            out.print(prefix); out.print(
8766                    Integer.toHexString(System.identityHashCode(filter.activity)));
8767                    out.print(' ');
8768                    filter.activity.printComponentShortName(out);
8769                    out.print(" filter ");
8770                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8771        }
8772
8773        @Override
8774        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8775            return filter.activity;
8776        }
8777
8778        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8779            PackageParser.Activity activity = (PackageParser.Activity)label;
8780            out.print(prefix); out.print(
8781                    Integer.toHexString(System.identityHashCode(activity)));
8782                    out.print(' ');
8783                    activity.printComponentShortName(out);
8784            if (count > 1) {
8785                out.print(" ("); out.print(count); out.print(" filters)");
8786            }
8787            out.println();
8788        }
8789
8790//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8791//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8792//            final List<ResolveInfo> retList = Lists.newArrayList();
8793//            while (i.hasNext()) {
8794//                final ResolveInfo resolveInfo = i.next();
8795//                if (isEnabledLP(resolveInfo.activityInfo)) {
8796//                    retList.add(resolveInfo);
8797//                }
8798//            }
8799//            return retList;
8800//        }
8801
8802        // Keys are String (activity class name), values are Activity.
8803        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8804                = new ArrayMap<ComponentName, PackageParser.Activity>();
8805        private int mFlags;
8806    }
8807
8808    private final class ServiceIntentResolver
8809            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8810        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8811                boolean defaultOnly, int userId) {
8812            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8813            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8814        }
8815
8816        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8817                int userId) {
8818            if (!sUserManager.exists(userId)) return null;
8819            mFlags = flags;
8820            return super.queryIntent(intent, resolvedType,
8821                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8822        }
8823
8824        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8825                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8826            if (!sUserManager.exists(userId)) return null;
8827            if (packageServices == null) {
8828                return null;
8829            }
8830            mFlags = flags;
8831            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8832            final int N = packageServices.size();
8833            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8834                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8835
8836            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8837            for (int i = 0; i < N; ++i) {
8838                intentFilters = packageServices.get(i).intents;
8839                if (intentFilters != null && intentFilters.size() > 0) {
8840                    PackageParser.ServiceIntentInfo[] array =
8841                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8842                    intentFilters.toArray(array);
8843                    listCut.add(array);
8844                }
8845            }
8846            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8847        }
8848
8849        public final void addService(PackageParser.Service s) {
8850            mServices.put(s.getComponentName(), s);
8851            if (DEBUG_SHOW_INFO) {
8852                Log.v(TAG, "  "
8853                        + (s.info.nonLocalizedLabel != null
8854                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8855                Log.v(TAG, "    Class=" + s.info.name);
8856            }
8857            final int NI = s.intents.size();
8858            int j;
8859            for (j=0; j<NI; j++) {
8860                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8861                if (DEBUG_SHOW_INFO) {
8862                    Log.v(TAG, "    IntentFilter:");
8863                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8864                }
8865                if (!intent.debugCheck()) {
8866                    Log.w(TAG, "==> For Service " + s.info.name);
8867                }
8868                addFilter(intent);
8869            }
8870        }
8871
8872        public final void removeService(PackageParser.Service s) {
8873            mServices.remove(s.getComponentName());
8874            if (DEBUG_SHOW_INFO) {
8875                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8876                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8877                Log.v(TAG, "    Class=" + s.info.name);
8878            }
8879            final int NI = s.intents.size();
8880            int j;
8881            for (j=0; j<NI; j++) {
8882                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8883                if (DEBUG_SHOW_INFO) {
8884                    Log.v(TAG, "    IntentFilter:");
8885                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8886                }
8887                removeFilter(intent);
8888            }
8889        }
8890
8891        @Override
8892        protected boolean allowFilterResult(
8893                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8894            ServiceInfo filterSi = filter.service.info;
8895            for (int i=dest.size()-1; i>=0; i--) {
8896                ServiceInfo destAi = dest.get(i).serviceInfo;
8897                if (destAi.name == filterSi.name
8898                        && destAi.packageName == filterSi.packageName) {
8899                    return false;
8900                }
8901            }
8902            return true;
8903        }
8904
8905        @Override
8906        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8907            return new PackageParser.ServiceIntentInfo[size];
8908        }
8909
8910        @Override
8911        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8912            if (!sUserManager.exists(userId)) return true;
8913            PackageParser.Package p = filter.service.owner;
8914            if (p != null) {
8915                PackageSetting ps = (PackageSetting)p.mExtras;
8916                if (ps != null) {
8917                    // System apps are never considered stopped for purposes of
8918                    // filtering, because there may be no way for the user to
8919                    // actually re-launch them.
8920                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8921                            && ps.getStopped(userId);
8922                }
8923            }
8924            return false;
8925        }
8926
8927        @Override
8928        protected boolean isPackageForFilter(String packageName,
8929                PackageParser.ServiceIntentInfo info) {
8930            return packageName.equals(info.service.owner.packageName);
8931        }
8932
8933        @Override
8934        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8935                int match, int userId) {
8936            if (!sUserManager.exists(userId)) return null;
8937            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8938            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8939                return null;
8940            }
8941            final PackageParser.Service service = info.service;
8942            if (mSafeMode && (service.info.applicationInfo.flags
8943                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8944                return null;
8945            }
8946            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8947            if (ps == null) {
8948                return null;
8949            }
8950            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8951                    ps.readUserState(userId), userId);
8952            if (si == null) {
8953                return null;
8954            }
8955            final ResolveInfo res = new ResolveInfo();
8956            res.serviceInfo = si;
8957            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8958                res.filter = filter;
8959            }
8960            res.priority = info.getPriority();
8961            res.preferredOrder = service.owner.mPreferredOrder;
8962            res.match = match;
8963            res.isDefault = info.hasDefault;
8964            res.labelRes = info.labelRes;
8965            res.nonLocalizedLabel = info.nonLocalizedLabel;
8966            res.icon = info.icon;
8967            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8968            return res;
8969        }
8970
8971        @Override
8972        protected void sortResults(List<ResolveInfo> results) {
8973            Collections.sort(results, mResolvePrioritySorter);
8974        }
8975
8976        @Override
8977        protected void dumpFilter(PrintWriter out, String prefix,
8978                PackageParser.ServiceIntentInfo filter) {
8979            out.print(prefix); out.print(
8980                    Integer.toHexString(System.identityHashCode(filter.service)));
8981                    out.print(' ');
8982                    filter.service.printComponentShortName(out);
8983                    out.print(" filter ");
8984                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8985        }
8986
8987        @Override
8988        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8989            return filter.service;
8990        }
8991
8992        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8993            PackageParser.Service service = (PackageParser.Service)label;
8994            out.print(prefix); out.print(
8995                    Integer.toHexString(System.identityHashCode(service)));
8996                    out.print(' ');
8997                    service.printComponentShortName(out);
8998            if (count > 1) {
8999                out.print(" ("); out.print(count); out.print(" filters)");
9000            }
9001            out.println();
9002        }
9003
9004//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9005//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9006//            final List<ResolveInfo> retList = Lists.newArrayList();
9007//            while (i.hasNext()) {
9008//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9009//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9010//                    retList.add(resolveInfo);
9011//                }
9012//            }
9013//            return retList;
9014//        }
9015
9016        // Keys are String (activity class name), values are Activity.
9017        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9018                = new ArrayMap<ComponentName, PackageParser.Service>();
9019        private int mFlags;
9020    };
9021
9022    private final class ProviderIntentResolver
9023            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9024        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9025                boolean defaultOnly, int userId) {
9026            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9027            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9028        }
9029
9030        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9031                int userId) {
9032            if (!sUserManager.exists(userId))
9033                return null;
9034            mFlags = flags;
9035            return super.queryIntent(intent, resolvedType,
9036                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9037        }
9038
9039        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9040                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9041            if (!sUserManager.exists(userId))
9042                return null;
9043            if (packageProviders == null) {
9044                return null;
9045            }
9046            mFlags = flags;
9047            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9048            final int N = packageProviders.size();
9049            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9050                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9051
9052            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9053            for (int i = 0; i < N; ++i) {
9054                intentFilters = packageProviders.get(i).intents;
9055                if (intentFilters != null && intentFilters.size() > 0) {
9056                    PackageParser.ProviderIntentInfo[] array =
9057                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9058                    intentFilters.toArray(array);
9059                    listCut.add(array);
9060                }
9061            }
9062            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9063        }
9064
9065        public final void addProvider(PackageParser.Provider p) {
9066            if (mProviders.containsKey(p.getComponentName())) {
9067                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9068                return;
9069            }
9070
9071            mProviders.put(p.getComponentName(), p);
9072            if (DEBUG_SHOW_INFO) {
9073                Log.v(TAG, "  "
9074                        + (p.info.nonLocalizedLabel != null
9075                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9076                Log.v(TAG, "    Class=" + p.info.name);
9077            }
9078            final int NI = p.intents.size();
9079            int j;
9080            for (j = 0; j < NI; j++) {
9081                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9082                if (DEBUG_SHOW_INFO) {
9083                    Log.v(TAG, "    IntentFilter:");
9084                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9085                }
9086                if (!intent.debugCheck()) {
9087                    Log.w(TAG, "==> For Provider " + p.info.name);
9088                }
9089                addFilter(intent);
9090            }
9091        }
9092
9093        public final void removeProvider(PackageParser.Provider p) {
9094            mProviders.remove(p.getComponentName());
9095            if (DEBUG_SHOW_INFO) {
9096                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9097                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9098                Log.v(TAG, "    Class=" + p.info.name);
9099            }
9100            final int NI = p.intents.size();
9101            int j;
9102            for (j = 0; j < NI; j++) {
9103                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9104                if (DEBUG_SHOW_INFO) {
9105                    Log.v(TAG, "    IntentFilter:");
9106                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9107                }
9108                removeFilter(intent);
9109            }
9110        }
9111
9112        @Override
9113        protected boolean allowFilterResult(
9114                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9115            ProviderInfo filterPi = filter.provider.info;
9116            for (int i = dest.size() - 1; i >= 0; i--) {
9117                ProviderInfo destPi = dest.get(i).providerInfo;
9118                if (destPi.name == filterPi.name
9119                        && destPi.packageName == filterPi.packageName) {
9120                    return false;
9121                }
9122            }
9123            return true;
9124        }
9125
9126        @Override
9127        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9128            return new PackageParser.ProviderIntentInfo[size];
9129        }
9130
9131        @Override
9132        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9133            if (!sUserManager.exists(userId))
9134                return true;
9135            PackageParser.Package p = filter.provider.owner;
9136            if (p != null) {
9137                PackageSetting ps = (PackageSetting) p.mExtras;
9138                if (ps != null) {
9139                    // System apps are never considered stopped for purposes of
9140                    // filtering, because there may be no way for the user to
9141                    // actually re-launch them.
9142                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9143                            && ps.getStopped(userId);
9144                }
9145            }
9146            return false;
9147        }
9148
9149        @Override
9150        protected boolean isPackageForFilter(String packageName,
9151                PackageParser.ProviderIntentInfo info) {
9152            return packageName.equals(info.provider.owner.packageName);
9153        }
9154
9155        @Override
9156        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9157                int match, int userId) {
9158            if (!sUserManager.exists(userId))
9159                return null;
9160            final PackageParser.ProviderIntentInfo info = filter;
9161            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9162                return null;
9163            }
9164            final PackageParser.Provider provider = info.provider;
9165            if (mSafeMode && (provider.info.applicationInfo.flags
9166                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9167                return null;
9168            }
9169            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9170            if (ps == null) {
9171                return null;
9172            }
9173            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9174                    ps.readUserState(userId), userId);
9175            if (pi == null) {
9176                return null;
9177            }
9178            final ResolveInfo res = new ResolveInfo();
9179            res.providerInfo = pi;
9180            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9181                res.filter = filter;
9182            }
9183            res.priority = info.getPriority();
9184            res.preferredOrder = provider.owner.mPreferredOrder;
9185            res.match = match;
9186            res.isDefault = info.hasDefault;
9187            res.labelRes = info.labelRes;
9188            res.nonLocalizedLabel = info.nonLocalizedLabel;
9189            res.icon = info.icon;
9190            res.system = res.providerInfo.applicationInfo.isSystemApp();
9191            return res;
9192        }
9193
9194        @Override
9195        protected void sortResults(List<ResolveInfo> results) {
9196            Collections.sort(results, mResolvePrioritySorter);
9197        }
9198
9199        @Override
9200        protected void dumpFilter(PrintWriter out, String prefix,
9201                PackageParser.ProviderIntentInfo filter) {
9202            out.print(prefix);
9203            out.print(
9204                    Integer.toHexString(System.identityHashCode(filter.provider)));
9205            out.print(' ');
9206            filter.provider.printComponentShortName(out);
9207            out.print(" filter ");
9208            out.println(Integer.toHexString(System.identityHashCode(filter)));
9209        }
9210
9211        @Override
9212        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9213            return filter.provider;
9214        }
9215
9216        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9217            PackageParser.Provider provider = (PackageParser.Provider)label;
9218            out.print(prefix); out.print(
9219                    Integer.toHexString(System.identityHashCode(provider)));
9220                    out.print(' ');
9221                    provider.printComponentShortName(out);
9222            if (count > 1) {
9223                out.print(" ("); out.print(count); out.print(" filters)");
9224            }
9225            out.println();
9226        }
9227
9228        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9229                = new ArrayMap<ComponentName, PackageParser.Provider>();
9230        private int mFlags;
9231    };
9232
9233    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9234            new Comparator<ResolveInfo>() {
9235        public int compare(ResolveInfo r1, ResolveInfo r2) {
9236            int v1 = r1.priority;
9237            int v2 = r2.priority;
9238            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9239            if (v1 != v2) {
9240                return (v1 > v2) ? -1 : 1;
9241            }
9242            v1 = r1.preferredOrder;
9243            v2 = r2.preferredOrder;
9244            if (v1 != v2) {
9245                return (v1 > v2) ? -1 : 1;
9246            }
9247            if (r1.isDefault != r2.isDefault) {
9248                return r1.isDefault ? -1 : 1;
9249            }
9250            v1 = r1.match;
9251            v2 = r2.match;
9252            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9253            if (v1 != v2) {
9254                return (v1 > v2) ? -1 : 1;
9255            }
9256            if (r1.system != r2.system) {
9257                return r1.system ? -1 : 1;
9258            }
9259            return 0;
9260        }
9261    };
9262
9263    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9264            new Comparator<ProviderInfo>() {
9265        public int compare(ProviderInfo p1, ProviderInfo p2) {
9266            final int v1 = p1.initOrder;
9267            final int v2 = p2.initOrder;
9268            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9269        }
9270    };
9271
9272    final void sendPackageBroadcast(final String action, final String pkg,
9273            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9274            final int[] userIds) {
9275        mHandler.post(new Runnable() {
9276            @Override
9277            public void run() {
9278                try {
9279                    final IActivityManager am = ActivityManagerNative.getDefault();
9280                    if (am == null) return;
9281                    final int[] resolvedUserIds;
9282                    if (userIds == null) {
9283                        resolvedUserIds = am.getRunningUserIds();
9284                    } else {
9285                        resolvedUserIds = userIds;
9286                    }
9287                    for (int id : resolvedUserIds) {
9288                        final Intent intent = new Intent(action,
9289                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9290                        if (extras != null) {
9291                            intent.putExtras(extras);
9292                        }
9293                        if (targetPkg != null) {
9294                            intent.setPackage(targetPkg);
9295                        }
9296                        // Modify the UID when posting to other users
9297                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9298                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9299                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9300                            intent.putExtra(Intent.EXTRA_UID, uid);
9301                        }
9302                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9303                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9304                        if (DEBUG_BROADCASTS) {
9305                            RuntimeException here = new RuntimeException("here");
9306                            here.fillInStackTrace();
9307                            Slog.d(TAG, "Sending to user " + id + ": "
9308                                    + intent.toShortString(false, true, false, false)
9309                                    + " " + intent.getExtras(), here);
9310                        }
9311                        am.broadcastIntent(null, intent, null, finishedReceiver,
9312                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9313                                null, finishedReceiver != null, false, id);
9314                    }
9315                } catch (RemoteException ex) {
9316                }
9317            }
9318        });
9319    }
9320
9321    /**
9322     * Check if the external storage media is available. This is true if there
9323     * is a mounted external storage medium or if the external storage is
9324     * emulated.
9325     */
9326    private boolean isExternalMediaAvailable() {
9327        return mMediaMounted || Environment.isExternalStorageEmulated();
9328    }
9329
9330    @Override
9331    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9332        // writer
9333        synchronized (mPackages) {
9334            if (!isExternalMediaAvailable()) {
9335                // If the external storage is no longer mounted at this point,
9336                // the caller may not have been able to delete all of this
9337                // packages files and can not delete any more.  Bail.
9338                return null;
9339            }
9340            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9341            if (lastPackage != null) {
9342                pkgs.remove(lastPackage);
9343            }
9344            if (pkgs.size() > 0) {
9345                return pkgs.get(0);
9346            }
9347        }
9348        return null;
9349    }
9350
9351    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9352        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9353                userId, andCode ? 1 : 0, packageName);
9354        if (mSystemReady) {
9355            msg.sendToTarget();
9356        } else {
9357            if (mPostSystemReadyMessages == null) {
9358                mPostSystemReadyMessages = new ArrayList<>();
9359            }
9360            mPostSystemReadyMessages.add(msg);
9361        }
9362    }
9363
9364    void startCleaningPackages() {
9365        // reader
9366        synchronized (mPackages) {
9367            if (!isExternalMediaAvailable()) {
9368                return;
9369            }
9370            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9371                return;
9372            }
9373        }
9374        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9375        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9376        IActivityManager am = ActivityManagerNative.getDefault();
9377        if (am != null) {
9378            try {
9379                am.startService(null, intent, null, mContext.getOpPackageName(),
9380                        UserHandle.USER_OWNER);
9381            } catch (RemoteException e) {
9382            }
9383        }
9384    }
9385
9386    @Override
9387    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9388            int installFlags, String installerPackageName, VerificationParams verificationParams,
9389            String packageAbiOverride) {
9390        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9391                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9392    }
9393
9394    @Override
9395    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9396            int installFlags, String installerPackageName, VerificationParams verificationParams,
9397            String packageAbiOverride, int userId) {
9398        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9399
9400        final int callingUid = Binder.getCallingUid();
9401        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9402
9403        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9404            try {
9405                if (observer != null) {
9406                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9407                }
9408            } catch (RemoteException re) {
9409            }
9410            return;
9411        }
9412
9413        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9414            installFlags |= PackageManager.INSTALL_FROM_ADB;
9415
9416        } else {
9417            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9418            // about installerPackageName.
9419
9420            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9421            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9422        }
9423
9424        UserHandle user;
9425        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9426            user = UserHandle.ALL;
9427        } else {
9428            user = new UserHandle(userId);
9429        }
9430
9431        // Only system components can circumvent runtime permissions when installing.
9432        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9433                && mContext.checkCallingOrSelfPermission(Manifest.permission
9434                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9435            throw new SecurityException("You need the "
9436                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9437                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9438        }
9439
9440        verificationParams.setInstallerUid(callingUid);
9441
9442        final File originFile = new File(originPath);
9443        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9444
9445        final Message msg = mHandler.obtainMessage(INIT_COPY);
9446        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9447                null, verificationParams, user, packageAbiOverride);
9448        mHandler.sendMessage(msg);
9449    }
9450
9451    void installStage(String packageName, File stagedDir, String stagedCid,
9452            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9453            String installerPackageName, int installerUid, UserHandle user) {
9454        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9455                params.referrerUri, installerUid, null);
9456        verifParams.setInstallerUid(installerUid);
9457
9458        final OriginInfo origin;
9459        if (stagedDir != null) {
9460            origin = OriginInfo.fromStagedFile(stagedDir);
9461        } else {
9462            origin = OriginInfo.fromStagedContainer(stagedCid);
9463        }
9464
9465        final Message msg = mHandler.obtainMessage(INIT_COPY);
9466        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9467                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9468        mHandler.sendMessage(msg);
9469    }
9470
9471    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9472        Bundle extras = new Bundle(1);
9473        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9474
9475        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9476                packageName, extras, null, null, new int[] {userId});
9477        try {
9478            IActivityManager am = ActivityManagerNative.getDefault();
9479            final boolean isSystem =
9480                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9481            if (isSystem && am.isUserRunning(userId, false)) {
9482                // The just-installed/enabled app is bundled on the system, so presumed
9483                // to be able to run automatically without needing an explicit launch.
9484                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9485                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9486                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9487                        .setPackage(packageName);
9488                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9489                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9490            }
9491        } catch (RemoteException e) {
9492            // shouldn't happen
9493            Slog.w(TAG, "Unable to bootstrap installed package", e);
9494        }
9495    }
9496
9497    @Override
9498    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9499            int userId) {
9500        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9501        PackageSetting pkgSetting;
9502        final int uid = Binder.getCallingUid();
9503        enforceCrossUserPermission(uid, userId, true, true,
9504                "setApplicationHiddenSetting for user " + userId);
9505
9506        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9507            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9508            return false;
9509        }
9510
9511        long callingId = Binder.clearCallingIdentity();
9512        try {
9513            boolean sendAdded = false;
9514            boolean sendRemoved = false;
9515            // writer
9516            synchronized (mPackages) {
9517                pkgSetting = mSettings.mPackages.get(packageName);
9518                if (pkgSetting == null) {
9519                    return false;
9520                }
9521                if (pkgSetting.getHidden(userId) != hidden) {
9522                    pkgSetting.setHidden(hidden, userId);
9523                    mSettings.writePackageRestrictionsLPr(userId);
9524                    if (hidden) {
9525                        sendRemoved = true;
9526                    } else {
9527                        sendAdded = true;
9528                    }
9529                }
9530            }
9531            if (sendAdded) {
9532                sendPackageAddedForUser(packageName, pkgSetting, userId);
9533                return true;
9534            }
9535            if (sendRemoved) {
9536                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9537                        "hiding pkg");
9538                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9539            }
9540        } finally {
9541            Binder.restoreCallingIdentity(callingId);
9542        }
9543        return false;
9544    }
9545
9546    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9547            int userId) {
9548        final PackageRemovedInfo info = new PackageRemovedInfo();
9549        info.removedPackage = packageName;
9550        info.removedUsers = new int[] {userId};
9551        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9552        info.sendBroadcast(false, false, false);
9553    }
9554
9555    /**
9556     * Returns true if application is not found or there was an error. Otherwise it returns
9557     * the hidden state of the package for the given user.
9558     */
9559    @Override
9560    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9561        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9562        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9563                false, "getApplicationHidden for user " + userId);
9564        PackageSetting pkgSetting;
9565        long callingId = Binder.clearCallingIdentity();
9566        try {
9567            // writer
9568            synchronized (mPackages) {
9569                pkgSetting = mSettings.mPackages.get(packageName);
9570                if (pkgSetting == null) {
9571                    return true;
9572                }
9573                return pkgSetting.getHidden(userId);
9574            }
9575        } finally {
9576            Binder.restoreCallingIdentity(callingId);
9577        }
9578    }
9579
9580    /**
9581     * @hide
9582     */
9583    @Override
9584    public int installExistingPackageAsUser(String packageName, int userId) {
9585        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9586                null);
9587        PackageSetting pkgSetting;
9588        final int uid = Binder.getCallingUid();
9589        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9590                + userId);
9591        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9592            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9593        }
9594
9595        long callingId = Binder.clearCallingIdentity();
9596        try {
9597            boolean sendAdded = false;
9598
9599            // writer
9600            synchronized (mPackages) {
9601                pkgSetting = mSettings.mPackages.get(packageName);
9602                if (pkgSetting == null) {
9603                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9604                }
9605                if (!pkgSetting.getInstalled(userId)) {
9606                    pkgSetting.setInstalled(true, userId);
9607                    pkgSetting.setHidden(false, userId);
9608                    mSettings.writePackageRestrictionsLPr(userId);
9609                    sendAdded = true;
9610                }
9611            }
9612
9613            if (sendAdded) {
9614                sendPackageAddedForUser(packageName, pkgSetting, userId);
9615            }
9616        } finally {
9617            Binder.restoreCallingIdentity(callingId);
9618        }
9619
9620        return PackageManager.INSTALL_SUCCEEDED;
9621    }
9622
9623    boolean isUserRestricted(int userId, String restrictionKey) {
9624        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9625        if (restrictions.getBoolean(restrictionKey, false)) {
9626            Log.w(TAG, "User is restricted: " + restrictionKey);
9627            return true;
9628        }
9629        return false;
9630    }
9631
9632    @Override
9633    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9634        mContext.enforceCallingOrSelfPermission(
9635                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9636                "Only package verification agents can verify applications");
9637
9638        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9639        final PackageVerificationResponse response = new PackageVerificationResponse(
9640                verificationCode, Binder.getCallingUid());
9641        msg.arg1 = id;
9642        msg.obj = response;
9643        mHandler.sendMessage(msg);
9644    }
9645
9646    @Override
9647    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9648            long millisecondsToDelay) {
9649        mContext.enforceCallingOrSelfPermission(
9650                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9651                "Only package verification agents can extend verification timeouts");
9652
9653        final PackageVerificationState state = mPendingVerification.get(id);
9654        final PackageVerificationResponse response = new PackageVerificationResponse(
9655                verificationCodeAtTimeout, Binder.getCallingUid());
9656
9657        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9658            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9659        }
9660        if (millisecondsToDelay < 0) {
9661            millisecondsToDelay = 0;
9662        }
9663        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9664                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9665            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9666        }
9667
9668        if ((state != null) && !state.timeoutExtended()) {
9669            state.extendTimeout();
9670
9671            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9672            msg.arg1 = id;
9673            msg.obj = response;
9674            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9675        }
9676    }
9677
9678    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9679            int verificationCode, UserHandle user) {
9680        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9681        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9682        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9683        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9684        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9685
9686        mContext.sendBroadcastAsUser(intent, user,
9687                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9688    }
9689
9690    private ComponentName matchComponentForVerifier(String packageName,
9691            List<ResolveInfo> receivers) {
9692        ActivityInfo targetReceiver = null;
9693
9694        final int NR = receivers.size();
9695        for (int i = 0; i < NR; i++) {
9696            final ResolveInfo info = receivers.get(i);
9697            if (info.activityInfo == null) {
9698                continue;
9699            }
9700
9701            if (packageName.equals(info.activityInfo.packageName)) {
9702                targetReceiver = info.activityInfo;
9703                break;
9704            }
9705        }
9706
9707        if (targetReceiver == null) {
9708            return null;
9709        }
9710
9711        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9712    }
9713
9714    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9715            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9716        if (pkgInfo.verifiers.length == 0) {
9717            return null;
9718        }
9719
9720        final int N = pkgInfo.verifiers.length;
9721        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9722        for (int i = 0; i < N; i++) {
9723            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9724
9725            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9726                    receivers);
9727            if (comp == null) {
9728                continue;
9729            }
9730
9731            final int verifierUid = getUidForVerifier(verifierInfo);
9732            if (verifierUid == -1) {
9733                continue;
9734            }
9735
9736            if (DEBUG_VERIFY) {
9737                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9738                        + " with the correct signature");
9739            }
9740            sufficientVerifiers.add(comp);
9741            verificationState.addSufficientVerifier(verifierUid);
9742        }
9743
9744        return sufficientVerifiers;
9745    }
9746
9747    private int getUidForVerifier(VerifierInfo verifierInfo) {
9748        synchronized (mPackages) {
9749            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9750            if (pkg == null) {
9751                return -1;
9752            } else if (pkg.mSignatures.length != 1) {
9753                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9754                        + " has more than one signature; ignoring");
9755                return -1;
9756            }
9757
9758            /*
9759             * If the public key of the package's signature does not match
9760             * our expected public key, then this is a different package and
9761             * we should skip.
9762             */
9763
9764            final byte[] expectedPublicKey;
9765            try {
9766                final Signature verifierSig = pkg.mSignatures[0];
9767                final PublicKey publicKey = verifierSig.getPublicKey();
9768                expectedPublicKey = publicKey.getEncoded();
9769            } catch (CertificateException e) {
9770                return -1;
9771            }
9772
9773            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9774
9775            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9776                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9777                        + " does not have the expected public key; ignoring");
9778                return -1;
9779            }
9780
9781            return pkg.applicationInfo.uid;
9782        }
9783    }
9784
9785    @Override
9786    public void finishPackageInstall(int token) {
9787        enforceSystemOrRoot("Only the system is allowed to finish installs");
9788
9789        if (DEBUG_INSTALL) {
9790            Slog.v(TAG, "BM finishing package install for " + token);
9791        }
9792
9793        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9794        mHandler.sendMessage(msg);
9795    }
9796
9797    /**
9798     * Get the verification agent timeout.
9799     *
9800     * @return verification timeout in milliseconds
9801     */
9802    private long getVerificationTimeout() {
9803        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9804                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9805                DEFAULT_VERIFICATION_TIMEOUT);
9806    }
9807
9808    /**
9809     * Get the default verification agent response code.
9810     *
9811     * @return default verification response code
9812     */
9813    private int getDefaultVerificationResponse() {
9814        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9815                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9816                DEFAULT_VERIFICATION_RESPONSE);
9817    }
9818
9819    /**
9820     * Check whether or not package verification has been enabled.
9821     *
9822     * @return true if verification should be performed
9823     */
9824    private boolean isVerificationEnabled(int userId, int installFlags) {
9825        if (!DEFAULT_VERIFY_ENABLE) {
9826            return false;
9827        }
9828
9829        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9830
9831        // Check if installing from ADB
9832        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9833            // Do not run verification in a test harness environment
9834            if (ActivityManager.isRunningInTestHarness()) {
9835                return false;
9836            }
9837            if (ensureVerifyAppsEnabled) {
9838                return true;
9839            }
9840            // Check if the developer does not want package verification for ADB installs
9841            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9842                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9843                return false;
9844            }
9845        }
9846
9847        if (ensureVerifyAppsEnabled) {
9848            return true;
9849        }
9850
9851        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9852                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9853    }
9854
9855    @Override
9856    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9857            throws RemoteException {
9858        mContext.enforceCallingOrSelfPermission(
9859                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9860                "Only intentfilter verification agents can verify applications");
9861
9862        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9863        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9864                Binder.getCallingUid(), verificationCode, failedDomains);
9865        msg.arg1 = id;
9866        msg.obj = response;
9867        mHandler.sendMessage(msg);
9868    }
9869
9870    @Override
9871    public int getIntentVerificationStatus(String packageName, int userId) {
9872        synchronized (mPackages) {
9873            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9874        }
9875    }
9876
9877    @Override
9878    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9879        mContext.enforceCallingOrSelfPermission(
9880                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9881
9882        boolean result = false;
9883        synchronized (mPackages) {
9884            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9885        }
9886        if (result) {
9887            scheduleWritePackageRestrictionsLocked(userId);
9888        }
9889        return result;
9890    }
9891
9892    @Override
9893    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9894        synchronized (mPackages) {
9895            return mSettings.getIntentFilterVerificationsLPr(packageName);
9896        }
9897    }
9898
9899    @Override
9900    public List<IntentFilter> getAllIntentFilters(String packageName) {
9901        if (TextUtils.isEmpty(packageName)) {
9902            return Collections.<IntentFilter>emptyList();
9903        }
9904        synchronized (mPackages) {
9905            PackageParser.Package pkg = mPackages.get(packageName);
9906            if (pkg == null || pkg.activities == null) {
9907                return Collections.<IntentFilter>emptyList();
9908            }
9909            final int count = pkg.activities.size();
9910            ArrayList<IntentFilter> result = new ArrayList<>();
9911            for (int n=0; n<count; n++) {
9912                PackageParser.Activity activity = pkg.activities.get(n);
9913                if (activity.intents != null || activity.intents.size() > 0) {
9914                    result.addAll(activity.intents);
9915                }
9916            }
9917            return result;
9918        }
9919    }
9920
9921    @Override
9922    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9923        mContext.enforceCallingOrSelfPermission(
9924                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9925
9926        synchronized (mPackages) {
9927            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9928            if (packageName != null) {
9929                result |= updateIntentVerificationStatus(packageName,
9930                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9931                        userId);
9932                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9933                        packageName, userId);
9934            }
9935            return result;
9936        }
9937    }
9938
9939    @Override
9940    public String getDefaultBrowserPackageName(int userId) {
9941        synchronized (mPackages) {
9942            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9943        }
9944    }
9945
9946    /**
9947     * Get the "allow unknown sources" setting.
9948     *
9949     * @return the current "allow unknown sources" setting
9950     */
9951    private int getUnknownSourcesSettings() {
9952        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9953                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9954                -1);
9955    }
9956
9957    @Override
9958    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9959        final int uid = Binder.getCallingUid();
9960        // writer
9961        synchronized (mPackages) {
9962            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9963            if (targetPackageSetting == null) {
9964                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9965            }
9966
9967            PackageSetting installerPackageSetting;
9968            if (installerPackageName != null) {
9969                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9970                if (installerPackageSetting == null) {
9971                    throw new IllegalArgumentException("Unknown installer package: "
9972                            + installerPackageName);
9973                }
9974            } else {
9975                installerPackageSetting = null;
9976            }
9977
9978            Signature[] callerSignature;
9979            Object obj = mSettings.getUserIdLPr(uid);
9980            if (obj != null) {
9981                if (obj instanceof SharedUserSetting) {
9982                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9983                } else if (obj instanceof PackageSetting) {
9984                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9985                } else {
9986                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9987                }
9988            } else {
9989                throw new SecurityException("Unknown calling uid " + uid);
9990            }
9991
9992            // Verify: can't set installerPackageName to a package that is
9993            // not signed with the same cert as the caller.
9994            if (installerPackageSetting != null) {
9995                if (compareSignatures(callerSignature,
9996                        installerPackageSetting.signatures.mSignatures)
9997                        != PackageManager.SIGNATURE_MATCH) {
9998                    throw new SecurityException(
9999                            "Caller does not have same cert as new installer package "
10000                            + installerPackageName);
10001                }
10002            }
10003
10004            // Verify: if target already has an installer package, it must
10005            // be signed with the same cert as the caller.
10006            if (targetPackageSetting.installerPackageName != null) {
10007                PackageSetting setting = mSettings.mPackages.get(
10008                        targetPackageSetting.installerPackageName);
10009                // If the currently set package isn't valid, then it's always
10010                // okay to change it.
10011                if (setting != null) {
10012                    if (compareSignatures(callerSignature,
10013                            setting.signatures.mSignatures)
10014                            != PackageManager.SIGNATURE_MATCH) {
10015                        throw new SecurityException(
10016                                "Caller does not have same cert as old installer package "
10017                                + targetPackageSetting.installerPackageName);
10018                    }
10019                }
10020            }
10021
10022            // Okay!
10023            targetPackageSetting.installerPackageName = installerPackageName;
10024            scheduleWriteSettingsLocked();
10025        }
10026    }
10027
10028    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10029        // Queue up an async operation since the package installation may take a little while.
10030        mHandler.post(new Runnable() {
10031            public void run() {
10032                mHandler.removeCallbacks(this);
10033                 // Result object to be returned
10034                PackageInstalledInfo res = new PackageInstalledInfo();
10035                res.returnCode = currentStatus;
10036                res.uid = -1;
10037                res.pkg = null;
10038                res.removedInfo = new PackageRemovedInfo();
10039                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10040                    args.doPreInstall(res.returnCode);
10041                    synchronized (mInstallLock) {
10042                        installPackageLI(args, res);
10043                    }
10044                    args.doPostInstall(res.returnCode, res.uid);
10045                }
10046
10047                // A restore should be performed at this point if (a) the install
10048                // succeeded, (b) the operation is not an update, and (c) the new
10049                // package has not opted out of backup participation.
10050                final boolean update = res.removedInfo.removedPackage != null;
10051                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10052                boolean doRestore = !update
10053                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10054
10055                // Set up the post-install work request bookkeeping.  This will be used
10056                // and cleaned up by the post-install event handling regardless of whether
10057                // there's a restore pass performed.  Token values are >= 1.
10058                int token;
10059                if (mNextInstallToken < 0) mNextInstallToken = 1;
10060                token = mNextInstallToken++;
10061
10062                PostInstallData data = new PostInstallData(args, res);
10063                mRunningInstalls.put(token, data);
10064                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10065
10066                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10067                    // Pass responsibility to the Backup Manager.  It will perform a
10068                    // restore if appropriate, then pass responsibility back to the
10069                    // Package Manager to run the post-install observer callbacks
10070                    // and broadcasts.
10071                    IBackupManager bm = IBackupManager.Stub.asInterface(
10072                            ServiceManager.getService(Context.BACKUP_SERVICE));
10073                    if (bm != null) {
10074                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10075                                + " to BM for possible restore");
10076                        try {
10077                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10078                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10079                            } else {
10080                                doRestore = false;
10081                            }
10082                        } catch (RemoteException e) {
10083                            // can't happen; the backup manager is local
10084                        } catch (Exception e) {
10085                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10086                            doRestore = false;
10087                        }
10088                    } else {
10089                        Slog.e(TAG, "Backup Manager not found!");
10090                        doRestore = false;
10091                    }
10092                }
10093
10094                if (!doRestore) {
10095                    // No restore possible, or the Backup Manager was mysteriously not
10096                    // available -- just fire the post-install work request directly.
10097                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10098                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10099                    mHandler.sendMessage(msg);
10100                }
10101            }
10102        });
10103    }
10104
10105    private abstract class HandlerParams {
10106        private static final int MAX_RETRIES = 4;
10107
10108        /**
10109         * Number of times startCopy() has been attempted and had a non-fatal
10110         * error.
10111         */
10112        private int mRetries = 0;
10113
10114        /** User handle for the user requesting the information or installation. */
10115        private final UserHandle mUser;
10116
10117        HandlerParams(UserHandle user) {
10118            mUser = user;
10119        }
10120
10121        UserHandle getUser() {
10122            return mUser;
10123        }
10124
10125        final boolean startCopy() {
10126            boolean res;
10127            try {
10128                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10129
10130                if (++mRetries > MAX_RETRIES) {
10131                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10132                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10133                    handleServiceError();
10134                    return false;
10135                } else {
10136                    handleStartCopy();
10137                    res = true;
10138                }
10139            } catch (RemoteException e) {
10140                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10141                mHandler.sendEmptyMessage(MCS_RECONNECT);
10142                res = false;
10143            }
10144            handleReturnCode();
10145            return res;
10146        }
10147
10148        final void serviceError() {
10149            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10150            handleServiceError();
10151            handleReturnCode();
10152        }
10153
10154        abstract void handleStartCopy() throws RemoteException;
10155        abstract void handleServiceError();
10156        abstract void handleReturnCode();
10157    }
10158
10159    class MeasureParams extends HandlerParams {
10160        private final PackageStats mStats;
10161        private boolean mSuccess;
10162
10163        private final IPackageStatsObserver mObserver;
10164
10165        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10166            super(new UserHandle(stats.userHandle));
10167            mObserver = observer;
10168            mStats = stats;
10169        }
10170
10171        @Override
10172        public String toString() {
10173            return "MeasureParams{"
10174                + Integer.toHexString(System.identityHashCode(this))
10175                + " " + mStats.packageName + "}";
10176        }
10177
10178        @Override
10179        void handleStartCopy() throws RemoteException {
10180            synchronized (mInstallLock) {
10181                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10182            }
10183
10184            if (mSuccess) {
10185                final boolean mounted;
10186                if (Environment.isExternalStorageEmulated()) {
10187                    mounted = true;
10188                } else {
10189                    final String status = Environment.getExternalStorageState();
10190                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10191                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10192                }
10193
10194                if (mounted) {
10195                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10196
10197                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10198                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10199
10200                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10201                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10202
10203                    // Always subtract cache size, since it's a subdirectory
10204                    mStats.externalDataSize -= mStats.externalCacheSize;
10205
10206                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10207                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10208
10209                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10210                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10211                }
10212            }
10213        }
10214
10215        @Override
10216        void handleReturnCode() {
10217            if (mObserver != null) {
10218                try {
10219                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10220                } catch (RemoteException e) {
10221                    Slog.i(TAG, "Observer no longer exists.");
10222                }
10223            }
10224        }
10225
10226        @Override
10227        void handleServiceError() {
10228            Slog.e(TAG, "Could not measure application " + mStats.packageName
10229                            + " external storage");
10230        }
10231    }
10232
10233    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10234            throws RemoteException {
10235        long result = 0;
10236        for (File path : paths) {
10237            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10238        }
10239        return result;
10240    }
10241
10242    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10243        for (File path : paths) {
10244            try {
10245                mcs.clearDirectory(path.getAbsolutePath());
10246            } catch (RemoteException e) {
10247            }
10248        }
10249    }
10250
10251    static class OriginInfo {
10252        /**
10253         * Location where install is coming from, before it has been
10254         * copied/renamed into place. This could be a single monolithic APK
10255         * file, or a cluster directory. This location may be untrusted.
10256         */
10257        final File file;
10258        final String cid;
10259
10260        /**
10261         * Flag indicating that {@link #file} or {@link #cid} has already been
10262         * staged, meaning downstream users don't need to defensively copy the
10263         * contents.
10264         */
10265        final boolean staged;
10266
10267        /**
10268         * Flag indicating that {@link #file} or {@link #cid} is an already
10269         * installed app that is being moved.
10270         */
10271        final boolean existing;
10272
10273        final String resolvedPath;
10274        final File resolvedFile;
10275
10276        static OriginInfo fromNothing() {
10277            return new OriginInfo(null, null, false, false);
10278        }
10279
10280        static OriginInfo fromUntrustedFile(File file) {
10281            return new OriginInfo(file, null, false, false);
10282        }
10283
10284        static OriginInfo fromExistingFile(File file) {
10285            return new OriginInfo(file, null, false, true);
10286        }
10287
10288        static OriginInfo fromStagedFile(File file) {
10289            return new OriginInfo(file, null, true, false);
10290        }
10291
10292        static OriginInfo fromStagedContainer(String cid) {
10293            return new OriginInfo(null, cid, true, false);
10294        }
10295
10296        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10297            this.file = file;
10298            this.cid = cid;
10299            this.staged = staged;
10300            this.existing = existing;
10301
10302            if (cid != null) {
10303                resolvedPath = PackageHelper.getSdDir(cid);
10304                resolvedFile = new File(resolvedPath);
10305            } else if (file != null) {
10306                resolvedPath = file.getAbsolutePath();
10307                resolvedFile = file;
10308            } else {
10309                resolvedPath = null;
10310                resolvedFile = null;
10311            }
10312        }
10313    }
10314
10315    class MoveInfo {
10316        final int moveId;
10317        final String fromUuid;
10318        final String toUuid;
10319        final String packageName;
10320        final String dataAppName;
10321        final int appId;
10322        final String seinfo;
10323
10324        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10325                String dataAppName, int appId, String seinfo) {
10326            this.moveId = moveId;
10327            this.fromUuid = fromUuid;
10328            this.toUuid = toUuid;
10329            this.packageName = packageName;
10330            this.dataAppName = dataAppName;
10331            this.appId = appId;
10332            this.seinfo = seinfo;
10333        }
10334    }
10335
10336    class InstallParams extends HandlerParams {
10337        final OriginInfo origin;
10338        final MoveInfo move;
10339        final IPackageInstallObserver2 observer;
10340        int installFlags;
10341        final String installerPackageName;
10342        final String volumeUuid;
10343        final VerificationParams verificationParams;
10344        private InstallArgs mArgs;
10345        private int mRet;
10346        final String packageAbiOverride;
10347
10348        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10349                int installFlags, String installerPackageName, String volumeUuid,
10350                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10351            super(user);
10352            this.origin = origin;
10353            this.move = move;
10354            this.observer = observer;
10355            this.installFlags = installFlags;
10356            this.installerPackageName = installerPackageName;
10357            this.volumeUuid = volumeUuid;
10358            this.verificationParams = verificationParams;
10359            this.packageAbiOverride = packageAbiOverride;
10360        }
10361
10362        @Override
10363        public String toString() {
10364            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10365                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10366        }
10367
10368        public ManifestDigest getManifestDigest() {
10369            if (verificationParams == null) {
10370                return null;
10371            }
10372            return verificationParams.getManifestDigest();
10373        }
10374
10375        private int installLocationPolicy(PackageInfoLite pkgLite) {
10376            String packageName = pkgLite.packageName;
10377            int installLocation = pkgLite.installLocation;
10378            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10379            // reader
10380            synchronized (mPackages) {
10381                PackageParser.Package pkg = mPackages.get(packageName);
10382                if (pkg != null) {
10383                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10384                        // Check for downgrading.
10385                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10386                            try {
10387                                checkDowngrade(pkg, pkgLite);
10388                            } catch (PackageManagerException e) {
10389                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10390                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10391                            }
10392                        }
10393                        // Check for updated system application.
10394                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10395                            if (onSd) {
10396                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10397                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10398                            }
10399                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10400                        } else {
10401                            if (onSd) {
10402                                // Install flag overrides everything.
10403                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10404                            }
10405                            // If current upgrade specifies particular preference
10406                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10407                                // Application explicitly specified internal.
10408                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10409                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10410                                // App explictly prefers external. Let policy decide
10411                            } else {
10412                                // Prefer previous location
10413                                if (isExternal(pkg)) {
10414                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10415                                }
10416                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10417                            }
10418                        }
10419                    } else {
10420                        // Invalid install. Return error code
10421                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10422                    }
10423                }
10424            }
10425            // All the special cases have been taken care of.
10426            // Return result based on recommended install location.
10427            if (onSd) {
10428                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10429            }
10430            return pkgLite.recommendedInstallLocation;
10431        }
10432
10433        /*
10434         * Invoke remote method to get package information and install
10435         * location values. Override install location based on default
10436         * policy if needed and then create install arguments based
10437         * on the install location.
10438         */
10439        public void handleStartCopy() throws RemoteException {
10440            int ret = PackageManager.INSTALL_SUCCEEDED;
10441
10442            // If we're already staged, we've firmly committed to an install location
10443            if (origin.staged) {
10444                if (origin.file != null) {
10445                    installFlags |= PackageManager.INSTALL_INTERNAL;
10446                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10447                } else if (origin.cid != null) {
10448                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10449                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10450                } else {
10451                    throw new IllegalStateException("Invalid stage location");
10452                }
10453            }
10454
10455            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10456            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10457
10458            PackageInfoLite pkgLite = null;
10459
10460            if (onInt && onSd) {
10461                // Check if both bits are set.
10462                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10463                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10464            } else {
10465                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10466                        packageAbiOverride);
10467
10468                /*
10469                 * If we have too little free space, try to free cache
10470                 * before giving up.
10471                 */
10472                if (!origin.staged && pkgLite.recommendedInstallLocation
10473                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10474                    // TODO: focus freeing disk space on the target device
10475                    final StorageManager storage = StorageManager.from(mContext);
10476                    final long lowThreshold = storage.getStorageLowBytes(
10477                            Environment.getDataDirectory());
10478
10479                    final long sizeBytes = mContainerService.calculateInstalledSize(
10480                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10481
10482                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10483                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10484                                installFlags, packageAbiOverride);
10485                    }
10486
10487                    /*
10488                     * The cache free must have deleted the file we
10489                     * downloaded to install.
10490                     *
10491                     * TODO: fix the "freeCache" call to not delete
10492                     *       the file we care about.
10493                     */
10494                    if (pkgLite.recommendedInstallLocation
10495                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10496                        pkgLite.recommendedInstallLocation
10497                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10498                    }
10499                }
10500            }
10501
10502            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10503                int loc = pkgLite.recommendedInstallLocation;
10504                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10505                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10506                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10507                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10508                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10509                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10510                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10511                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10512                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10513                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10514                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10515                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10516                } else {
10517                    // Override with defaults if needed.
10518                    loc = installLocationPolicy(pkgLite);
10519                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10520                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10521                    } else if (!onSd && !onInt) {
10522                        // Override install location with flags
10523                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10524                            // Set the flag to install on external media.
10525                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10526                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10527                        } else {
10528                            // Make sure the flag for installing on external
10529                            // media is unset
10530                            installFlags |= PackageManager.INSTALL_INTERNAL;
10531                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10532                        }
10533                    }
10534                }
10535            }
10536
10537            final InstallArgs args = createInstallArgs(this);
10538            mArgs = args;
10539
10540            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10541                 /*
10542                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10543                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10544                 */
10545                int userIdentifier = getUser().getIdentifier();
10546                if (userIdentifier == UserHandle.USER_ALL
10547                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10548                    userIdentifier = UserHandle.USER_OWNER;
10549                }
10550
10551                /*
10552                 * Determine if we have any installed package verifiers. If we
10553                 * do, then we'll defer to them to verify the packages.
10554                 */
10555                final int requiredUid = mRequiredVerifierPackage == null ? -1
10556                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10557                if (!origin.existing && requiredUid != -1
10558                        && isVerificationEnabled(userIdentifier, installFlags)) {
10559                    final Intent verification = new Intent(
10560                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10561                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10562                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10563                            PACKAGE_MIME_TYPE);
10564                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10565
10566                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10567                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10568                            0 /* TODO: Which userId? */);
10569
10570                    if (DEBUG_VERIFY) {
10571                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10572                                + verification.toString() + " with " + pkgLite.verifiers.length
10573                                + " optional verifiers");
10574                    }
10575
10576                    final int verificationId = mPendingVerificationToken++;
10577
10578                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10579
10580                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10581                            installerPackageName);
10582
10583                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10584                            installFlags);
10585
10586                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10587                            pkgLite.packageName);
10588
10589                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10590                            pkgLite.versionCode);
10591
10592                    if (verificationParams != null) {
10593                        if (verificationParams.getVerificationURI() != null) {
10594                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10595                                 verificationParams.getVerificationURI());
10596                        }
10597                        if (verificationParams.getOriginatingURI() != null) {
10598                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10599                                  verificationParams.getOriginatingURI());
10600                        }
10601                        if (verificationParams.getReferrer() != null) {
10602                            verification.putExtra(Intent.EXTRA_REFERRER,
10603                                  verificationParams.getReferrer());
10604                        }
10605                        if (verificationParams.getOriginatingUid() >= 0) {
10606                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10607                                  verificationParams.getOriginatingUid());
10608                        }
10609                        if (verificationParams.getInstallerUid() >= 0) {
10610                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10611                                  verificationParams.getInstallerUid());
10612                        }
10613                    }
10614
10615                    final PackageVerificationState verificationState = new PackageVerificationState(
10616                            requiredUid, args);
10617
10618                    mPendingVerification.append(verificationId, verificationState);
10619
10620                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10621                            receivers, verificationState);
10622
10623                    // Apps installed for "all" users use the device owner to verify the app
10624                    UserHandle verifierUser = getUser();
10625                    if (verifierUser == UserHandle.ALL) {
10626                        verifierUser = UserHandle.OWNER;
10627                    }
10628
10629                    /*
10630                     * If any sufficient verifiers were listed in the package
10631                     * manifest, attempt to ask them.
10632                     */
10633                    if (sufficientVerifiers != null) {
10634                        final int N = sufficientVerifiers.size();
10635                        if (N == 0) {
10636                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10637                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10638                        } else {
10639                            for (int i = 0; i < N; i++) {
10640                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10641
10642                                final Intent sufficientIntent = new Intent(verification);
10643                                sufficientIntent.setComponent(verifierComponent);
10644                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10645                            }
10646                        }
10647                    }
10648
10649                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10650                            mRequiredVerifierPackage, receivers);
10651                    if (ret == PackageManager.INSTALL_SUCCEEDED
10652                            && mRequiredVerifierPackage != null) {
10653                        /*
10654                         * Send the intent to the required verification agent,
10655                         * but only start the verification timeout after the
10656                         * target BroadcastReceivers have run.
10657                         */
10658                        verification.setComponent(requiredVerifierComponent);
10659                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10660                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10661                                new BroadcastReceiver() {
10662                                    @Override
10663                                    public void onReceive(Context context, Intent intent) {
10664                                        final Message msg = mHandler
10665                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10666                                        msg.arg1 = verificationId;
10667                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10668                                    }
10669                                }, null, 0, null, null);
10670
10671                        /*
10672                         * We don't want the copy to proceed until verification
10673                         * succeeds, so null out this field.
10674                         */
10675                        mArgs = null;
10676                    }
10677                } else {
10678                    /*
10679                     * No package verification is enabled, so immediately start
10680                     * the remote call to initiate copy using temporary file.
10681                     */
10682                    ret = args.copyApk(mContainerService, true);
10683                }
10684            }
10685
10686            mRet = ret;
10687        }
10688
10689        @Override
10690        void handleReturnCode() {
10691            // If mArgs is null, then MCS couldn't be reached. When it
10692            // reconnects, it will try again to install. At that point, this
10693            // will succeed.
10694            if (mArgs != null) {
10695                processPendingInstall(mArgs, mRet);
10696            }
10697        }
10698
10699        @Override
10700        void handleServiceError() {
10701            mArgs = createInstallArgs(this);
10702            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10703        }
10704
10705        public boolean isForwardLocked() {
10706            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10707        }
10708    }
10709
10710    /**
10711     * Used during creation of InstallArgs
10712     *
10713     * @param installFlags package installation flags
10714     * @return true if should be installed on external storage
10715     */
10716    private static boolean installOnExternalAsec(int installFlags) {
10717        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10718            return false;
10719        }
10720        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10721            return true;
10722        }
10723        return false;
10724    }
10725
10726    /**
10727     * Used during creation of InstallArgs
10728     *
10729     * @param installFlags package installation flags
10730     * @return true if should be installed as forward locked
10731     */
10732    private static boolean installForwardLocked(int installFlags) {
10733        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10734    }
10735
10736    private InstallArgs createInstallArgs(InstallParams params) {
10737        if (params.move != null) {
10738            return new MoveInstallArgs(params);
10739        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10740            return new AsecInstallArgs(params);
10741        } else {
10742            return new FileInstallArgs(params);
10743        }
10744    }
10745
10746    /**
10747     * Create args that describe an existing installed package. Typically used
10748     * when cleaning up old installs, or used as a move source.
10749     */
10750    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10751            String resourcePath, String[] instructionSets) {
10752        final boolean isInAsec;
10753        if (installOnExternalAsec(installFlags)) {
10754            /* Apps on SD card are always in ASEC containers. */
10755            isInAsec = true;
10756        } else if (installForwardLocked(installFlags)
10757                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10758            /*
10759             * Forward-locked apps are only in ASEC containers if they're the
10760             * new style
10761             */
10762            isInAsec = true;
10763        } else {
10764            isInAsec = false;
10765        }
10766
10767        if (isInAsec) {
10768            return new AsecInstallArgs(codePath, instructionSets,
10769                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10770        } else {
10771            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10772        }
10773    }
10774
10775    static abstract class InstallArgs {
10776        /** @see InstallParams#origin */
10777        final OriginInfo origin;
10778        /** @see InstallParams#move */
10779        final MoveInfo move;
10780
10781        final IPackageInstallObserver2 observer;
10782        // Always refers to PackageManager flags only
10783        final int installFlags;
10784        final String installerPackageName;
10785        final String volumeUuid;
10786        final ManifestDigest manifestDigest;
10787        final UserHandle user;
10788        final String abiOverride;
10789
10790        // The list of instruction sets supported by this app. This is currently
10791        // only used during the rmdex() phase to clean up resources. We can get rid of this
10792        // if we move dex files under the common app path.
10793        /* nullable */ String[] instructionSets;
10794
10795        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10796                int installFlags, String installerPackageName, String volumeUuid,
10797                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10798                String abiOverride) {
10799            this.origin = origin;
10800            this.move = move;
10801            this.installFlags = installFlags;
10802            this.observer = observer;
10803            this.installerPackageName = installerPackageName;
10804            this.volumeUuid = volumeUuid;
10805            this.manifestDigest = manifestDigest;
10806            this.user = user;
10807            this.instructionSets = instructionSets;
10808            this.abiOverride = abiOverride;
10809        }
10810
10811        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10812        abstract int doPreInstall(int status);
10813
10814        /**
10815         * Rename package into final resting place. All paths on the given
10816         * scanned package should be updated to reflect the rename.
10817         */
10818        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10819        abstract int doPostInstall(int status, int uid);
10820
10821        /** @see PackageSettingBase#codePathString */
10822        abstract String getCodePath();
10823        /** @see PackageSettingBase#resourcePathString */
10824        abstract String getResourcePath();
10825
10826        // Need installer lock especially for dex file removal.
10827        abstract void cleanUpResourcesLI();
10828        abstract boolean doPostDeleteLI(boolean delete);
10829
10830        /**
10831         * Called before the source arguments are copied. This is used mostly
10832         * for MoveParams when it needs to read the source file to put it in the
10833         * destination.
10834         */
10835        int doPreCopy() {
10836            return PackageManager.INSTALL_SUCCEEDED;
10837        }
10838
10839        /**
10840         * Called after the source arguments are copied. This is used mostly for
10841         * MoveParams when it needs to read the source file to put it in the
10842         * destination.
10843         *
10844         * @return
10845         */
10846        int doPostCopy(int uid) {
10847            return PackageManager.INSTALL_SUCCEEDED;
10848        }
10849
10850        protected boolean isFwdLocked() {
10851            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10852        }
10853
10854        protected boolean isExternalAsec() {
10855            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10856        }
10857
10858        UserHandle getUser() {
10859            return user;
10860        }
10861    }
10862
10863    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10864        if (!allCodePaths.isEmpty()) {
10865            if (instructionSets == null) {
10866                throw new IllegalStateException("instructionSet == null");
10867            }
10868            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10869            for (String codePath : allCodePaths) {
10870                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10871                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10872                    if (retCode < 0) {
10873                        Slog.w(TAG, "Couldn't remove dex file for package: "
10874                                + " at location " + codePath + ", retcode=" + retCode);
10875                        // we don't consider this to be a failure of the core package deletion
10876                    }
10877                }
10878            }
10879        }
10880    }
10881
10882    /**
10883     * Logic to handle installation of non-ASEC applications, including copying
10884     * and renaming logic.
10885     */
10886    class FileInstallArgs extends InstallArgs {
10887        private File codeFile;
10888        private File resourceFile;
10889
10890        // Example topology:
10891        // /data/app/com.example/base.apk
10892        // /data/app/com.example/split_foo.apk
10893        // /data/app/com.example/lib/arm/libfoo.so
10894        // /data/app/com.example/lib/arm64/libfoo.so
10895        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10896
10897        /** New install */
10898        FileInstallArgs(InstallParams params) {
10899            super(params.origin, params.move, params.observer, params.installFlags,
10900                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10901                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10902            if (isFwdLocked()) {
10903                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10904            }
10905        }
10906
10907        /** Existing install */
10908        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10909            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10910                    null);
10911            this.codeFile = (codePath != null) ? new File(codePath) : null;
10912            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10913        }
10914
10915        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10916            if (origin.staged) {
10917                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10918                codeFile = origin.file;
10919                resourceFile = origin.file;
10920                return PackageManager.INSTALL_SUCCEEDED;
10921            }
10922
10923            try {
10924                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10925                codeFile = tempDir;
10926                resourceFile = tempDir;
10927            } catch (IOException e) {
10928                Slog.w(TAG, "Failed to create copy file: " + e);
10929                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10930            }
10931
10932            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10933                @Override
10934                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10935                    if (!FileUtils.isValidExtFilename(name)) {
10936                        throw new IllegalArgumentException("Invalid filename: " + name);
10937                    }
10938                    try {
10939                        final File file = new File(codeFile, name);
10940                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10941                                O_RDWR | O_CREAT, 0644);
10942                        Os.chmod(file.getAbsolutePath(), 0644);
10943                        return new ParcelFileDescriptor(fd);
10944                    } catch (ErrnoException e) {
10945                        throw new RemoteException("Failed to open: " + e.getMessage());
10946                    }
10947                }
10948            };
10949
10950            int ret = PackageManager.INSTALL_SUCCEEDED;
10951            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10952            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10953                Slog.e(TAG, "Failed to copy package");
10954                return ret;
10955            }
10956
10957            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10958            NativeLibraryHelper.Handle handle = null;
10959            try {
10960                handle = NativeLibraryHelper.Handle.create(codeFile);
10961                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10962                        abiOverride);
10963            } catch (IOException e) {
10964                Slog.e(TAG, "Copying native libraries failed", e);
10965                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10966            } finally {
10967                IoUtils.closeQuietly(handle);
10968            }
10969
10970            return ret;
10971        }
10972
10973        int doPreInstall(int status) {
10974            if (status != PackageManager.INSTALL_SUCCEEDED) {
10975                cleanUp();
10976            }
10977            return status;
10978        }
10979
10980        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10981            if (status != PackageManager.INSTALL_SUCCEEDED) {
10982                cleanUp();
10983                return false;
10984            }
10985
10986            final File targetDir = codeFile.getParentFile();
10987            final File beforeCodeFile = codeFile;
10988            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10989
10990            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10991            try {
10992                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10993            } catch (ErrnoException e) {
10994                Slog.w(TAG, "Failed to rename", e);
10995                return false;
10996            }
10997
10998            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10999                Slog.w(TAG, "Failed to restorecon");
11000                return false;
11001            }
11002
11003            // Reflect the rename internally
11004            codeFile = afterCodeFile;
11005            resourceFile = afterCodeFile;
11006
11007            // Reflect the rename in scanned details
11008            pkg.codePath = afterCodeFile.getAbsolutePath();
11009            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11010                    pkg.baseCodePath);
11011            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11012                    pkg.splitCodePaths);
11013
11014            // Reflect the rename in app info
11015            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11016            pkg.applicationInfo.setCodePath(pkg.codePath);
11017            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11018            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11019            pkg.applicationInfo.setResourcePath(pkg.codePath);
11020            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11021            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11022
11023            return true;
11024        }
11025
11026        int doPostInstall(int status, int uid) {
11027            if (status != PackageManager.INSTALL_SUCCEEDED) {
11028                cleanUp();
11029            }
11030            return status;
11031        }
11032
11033        @Override
11034        String getCodePath() {
11035            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11036        }
11037
11038        @Override
11039        String getResourcePath() {
11040            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11041        }
11042
11043        private boolean cleanUp() {
11044            if (codeFile == null || !codeFile.exists()) {
11045                return false;
11046            }
11047
11048            if (codeFile.isDirectory()) {
11049                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11050            } else {
11051                codeFile.delete();
11052            }
11053
11054            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11055                resourceFile.delete();
11056            }
11057
11058            return true;
11059        }
11060
11061        void cleanUpResourcesLI() {
11062            // Try enumerating all code paths before deleting
11063            List<String> allCodePaths = Collections.EMPTY_LIST;
11064            if (codeFile != null && codeFile.exists()) {
11065                try {
11066                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11067                    allCodePaths = pkg.getAllCodePaths();
11068                } catch (PackageParserException e) {
11069                    // Ignored; we tried our best
11070                }
11071            }
11072
11073            cleanUp();
11074            removeDexFiles(allCodePaths, instructionSets);
11075        }
11076
11077        boolean doPostDeleteLI(boolean delete) {
11078            // XXX err, shouldn't we respect the delete flag?
11079            cleanUpResourcesLI();
11080            return true;
11081        }
11082    }
11083
11084    private boolean isAsecExternal(String cid) {
11085        final String asecPath = PackageHelper.getSdFilesystem(cid);
11086        return !asecPath.startsWith(mAsecInternalPath);
11087    }
11088
11089    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11090            PackageManagerException {
11091        if (copyRet < 0) {
11092            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11093                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11094                throw new PackageManagerException(copyRet, message);
11095            }
11096        }
11097    }
11098
11099    /**
11100     * Extract the MountService "container ID" from the full code path of an
11101     * .apk.
11102     */
11103    static String cidFromCodePath(String fullCodePath) {
11104        int eidx = fullCodePath.lastIndexOf("/");
11105        String subStr1 = fullCodePath.substring(0, eidx);
11106        int sidx = subStr1.lastIndexOf("/");
11107        return subStr1.substring(sidx+1, eidx);
11108    }
11109
11110    /**
11111     * Logic to handle installation of ASEC applications, including copying and
11112     * renaming logic.
11113     */
11114    class AsecInstallArgs extends InstallArgs {
11115        static final String RES_FILE_NAME = "pkg.apk";
11116        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11117
11118        String cid;
11119        String packagePath;
11120        String resourcePath;
11121
11122        /** New install */
11123        AsecInstallArgs(InstallParams params) {
11124            super(params.origin, params.move, params.observer, params.installFlags,
11125                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11126                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11127        }
11128
11129        /** Existing install */
11130        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11131                        boolean isExternal, boolean isForwardLocked) {
11132            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11133                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11134                    instructionSets, null);
11135            // Hackily pretend we're still looking at a full code path
11136            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11137                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11138            }
11139
11140            // Extract cid from fullCodePath
11141            int eidx = fullCodePath.lastIndexOf("/");
11142            String subStr1 = fullCodePath.substring(0, eidx);
11143            int sidx = subStr1.lastIndexOf("/");
11144            cid = subStr1.substring(sidx+1, eidx);
11145            setMountPath(subStr1);
11146        }
11147
11148        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11149            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11150                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11151                    instructionSets, null);
11152            this.cid = cid;
11153            setMountPath(PackageHelper.getSdDir(cid));
11154        }
11155
11156        void createCopyFile() {
11157            cid = mInstallerService.allocateExternalStageCidLegacy();
11158        }
11159
11160        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11161            if (origin.staged) {
11162                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11163                cid = origin.cid;
11164                setMountPath(PackageHelper.getSdDir(cid));
11165                return PackageManager.INSTALL_SUCCEEDED;
11166            }
11167
11168            if (temp) {
11169                createCopyFile();
11170            } else {
11171                /*
11172                 * Pre-emptively destroy the container since it's destroyed if
11173                 * copying fails due to it existing anyway.
11174                 */
11175                PackageHelper.destroySdDir(cid);
11176            }
11177
11178            final String newMountPath = imcs.copyPackageToContainer(
11179                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11180                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11181
11182            if (newMountPath != null) {
11183                setMountPath(newMountPath);
11184                return PackageManager.INSTALL_SUCCEEDED;
11185            } else {
11186                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11187            }
11188        }
11189
11190        @Override
11191        String getCodePath() {
11192            return packagePath;
11193        }
11194
11195        @Override
11196        String getResourcePath() {
11197            return resourcePath;
11198        }
11199
11200        int doPreInstall(int status) {
11201            if (status != PackageManager.INSTALL_SUCCEEDED) {
11202                // Destroy container
11203                PackageHelper.destroySdDir(cid);
11204            } else {
11205                boolean mounted = PackageHelper.isContainerMounted(cid);
11206                if (!mounted) {
11207                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11208                            Process.SYSTEM_UID);
11209                    if (newMountPath != null) {
11210                        setMountPath(newMountPath);
11211                    } else {
11212                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11213                    }
11214                }
11215            }
11216            return status;
11217        }
11218
11219        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11220            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11221            String newMountPath = null;
11222            if (PackageHelper.isContainerMounted(cid)) {
11223                // Unmount the container
11224                if (!PackageHelper.unMountSdDir(cid)) {
11225                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11226                    return false;
11227                }
11228            }
11229            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11230                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11231                        " which might be stale. Will try to clean up.");
11232                // Clean up the stale container and proceed to recreate.
11233                if (!PackageHelper.destroySdDir(newCacheId)) {
11234                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11235                    return false;
11236                }
11237                // Successfully cleaned up stale container. Try to rename again.
11238                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11239                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11240                            + " inspite of cleaning it up.");
11241                    return false;
11242                }
11243            }
11244            if (!PackageHelper.isContainerMounted(newCacheId)) {
11245                Slog.w(TAG, "Mounting container " + newCacheId);
11246                newMountPath = PackageHelper.mountSdDir(newCacheId,
11247                        getEncryptKey(), Process.SYSTEM_UID);
11248            } else {
11249                newMountPath = PackageHelper.getSdDir(newCacheId);
11250            }
11251            if (newMountPath == null) {
11252                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11253                return false;
11254            }
11255            Log.i(TAG, "Succesfully renamed " + cid +
11256                    " to " + newCacheId +
11257                    " at new path: " + newMountPath);
11258            cid = newCacheId;
11259
11260            final File beforeCodeFile = new File(packagePath);
11261            setMountPath(newMountPath);
11262            final File afterCodeFile = new File(packagePath);
11263
11264            // Reflect the rename in scanned details
11265            pkg.codePath = afterCodeFile.getAbsolutePath();
11266            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11267                    pkg.baseCodePath);
11268            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11269                    pkg.splitCodePaths);
11270
11271            // Reflect the rename in app info
11272            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11273            pkg.applicationInfo.setCodePath(pkg.codePath);
11274            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11275            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11276            pkg.applicationInfo.setResourcePath(pkg.codePath);
11277            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11278            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11279
11280            return true;
11281        }
11282
11283        private void setMountPath(String mountPath) {
11284            final File mountFile = new File(mountPath);
11285
11286            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11287            if (monolithicFile.exists()) {
11288                packagePath = monolithicFile.getAbsolutePath();
11289                if (isFwdLocked()) {
11290                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11291                } else {
11292                    resourcePath = packagePath;
11293                }
11294            } else {
11295                packagePath = mountFile.getAbsolutePath();
11296                resourcePath = packagePath;
11297            }
11298        }
11299
11300        int doPostInstall(int status, int uid) {
11301            if (status != PackageManager.INSTALL_SUCCEEDED) {
11302                cleanUp();
11303            } else {
11304                final int groupOwner;
11305                final String protectedFile;
11306                if (isFwdLocked()) {
11307                    groupOwner = UserHandle.getSharedAppGid(uid);
11308                    protectedFile = RES_FILE_NAME;
11309                } else {
11310                    groupOwner = -1;
11311                    protectedFile = null;
11312                }
11313
11314                if (uid < Process.FIRST_APPLICATION_UID
11315                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11316                    Slog.e(TAG, "Failed to finalize " + cid);
11317                    PackageHelper.destroySdDir(cid);
11318                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11319                }
11320
11321                boolean mounted = PackageHelper.isContainerMounted(cid);
11322                if (!mounted) {
11323                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11324                }
11325            }
11326            return status;
11327        }
11328
11329        private void cleanUp() {
11330            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11331
11332            // Destroy secure container
11333            PackageHelper.destroySdDir(cid);
11334        }
11335
11336        private List<String> getAllCodePaths() {
11337            final File codeFile = new File(getCodePath());
11338            if (codeFile != null && codeFile.exists()) {
11339                try {
11340                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11341                    return pkg.getAllCodePaths();
11342                } catch (PackageParserException e) {
11343                    // Ignored; we tried our best
11344                }
11345            }
11346            return Collections.EMPTY_LIST;
11347        }
11348
11349        void cleanUpResourcesLI() {
11350            // Enumerate all code paths before deleting
11351            cleanUpResourcesLI(getAllCodePaths());
11352        }
11353
11354        private void cleanUpResourcesLI(List<String> allCodePaths) {
11355            cleanUp();
11356            removeDexFiles(allCodePaths, instructionSets);
11357        }
11358
11359        String getPackageName() {
11360            return getAsecPackageName(cid);
11361        }
11362
11363        boolean doPostDeleteLI(boolean delete) {
11364            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11365            final List<String> allCodePaths = getAllCodePaths();
11366            boolean mounted = PackageHelper.isContainerMounted(cid);
11367            if (mounted) {
11368                // Unmount first
11369                if (PackageHelper.unMountSdDir(cid)) {
11370                    mounted = false;
11371                }
11372            }
11373            if (!mounted && delete) {
11374                cleanUpResourcesLI(allCodePaths);
11375            }
11376            return !mounted;
11377        }
11378
11379        @Override
11380        int doPreCopy() {
11381            if (isFwdLocked()) {
11382                if (!PackageHelper.fixSdPermissions(cid,
11383                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11384                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11385                }
11386            }
11387
11388            return PackageManager.INSTALL_SUCCEEDED;
11389        }
11390
11391        @Override
11392        int doPostCopy(int uid) {
11393            if (isFwdLocked()) {
11394                if (uid < Process.FIRST_APPLICATION_UID
11395                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11396                                RES_FILE_NAME)) {
11397                    Slog.e(TAG, "Failed to finalize " + cid);
11398                    PackageHelper.destroySdDir(cid);
11399                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11400                }
11401            }
11402
11403            return PackageManager.INSTALL_SUCCEEDED;
11404        }
11405    }
11406
11407    /**
11408     * Logic to handle movement of existing installed applications.
11409     */
11410    class MoveInstallArgs extends InstallArgs {
11411        private File codeFile;
11412        private File resourceFile;
11413
11414        /** New install */
11415        MoveInstallArgs(InstallParams params) {
11416            super(params.origin, params.move, params.observer, params.installFlags,
11417                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11418                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11419        }
11420
11421        int copyApk(IMediaContainerService imcs, boolean temp) {
11422            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11423                    + move.fromUuid + " to " + move.toUuid);
11424            synchronized (mInstaller) {
11425                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11426                        move.dataAppName, move.appId, move.seinfo) != 0) {
11427                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11428                }
11429            }
11430
11431            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11432            resourceFile = codeFile;
11433            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11434
11435            return PackageManager.INSTALL_SUCCEEDED;
11436        }
11437
11438        int doPreInstall(int status) {
11439            if (status != PackageManager.INSTALL_SUCCEEDED) {
11440                cleanUp(move.toUuid);
11441            }
11442            return status;
11443        }
11444
11445        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11446            if (status != PackageManager.INSTALL_SUCCEEDED) {
11447                cleanUp(move.toUuid);
11448                return false;
11449            }
11450
11451            // Reflect the move in app info
11452            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11453            pkg.applicationInfo.setCodePath(pkg.codePath);
11454            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11455            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11456            pkg.applicationInfo.setResourcePath(pkg.codePath);
11457            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11458            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11459
11460            return true;
11461        }
11462
11463        int doPostInstall(int status, int uid) {
11464            if (status == PackageManager.INSTALL_SUCCEEDED) {
11465                cleanUp(move.fromUuid);
11466            } else {
11467                cleanUp(move.toUuid);
11468            }
11469            return status;
11470        }
11471
11472        @Override
11473        String getCodePath() {
11474            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11475        }
11476
11477        @Override
11478        String getResourcePath() {
11479            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11480        }
11481
11482        private boolean cleanUp(String volumeUuid) {
11483            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11484                    move.dataAppName);
11485            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11486            synchronized (mInstallLock) {
11487                // Clean up both app data and code
11488                removeDataDirsLI(volumeUuid, move.packageName);
11489                if (codeFile.isDirectory()) {
11490                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11491                } else {
11492                    codeFile.delete();
11493                }
11494            }
11495            return true;
11496        }
11497
11498        void cleanUpResourcesLI() {
11499            throw new UnsupportedOperationException();
11500        }
11501
11502        boolean doPostDeleteLI(boolean delete) {
11503            throw new UnsupportedOperationException();
11504        }
11505    }
11506
11507    static String getAsecPackageName(String packageCid) {
11508        int idx = packageCid.lastIndexOf("-");
11509        if (idx == -1) {
11510            return packageCid;
11511        }
11512        return packageCid.substring(0, idx);
11513    }
11514
11515    // Utility method used to create code paths based on package name and available index.
11516    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11517        String idxStr = "";
11518        int idx = 1;
11519        // Fall back to default value of idx=1 if prefix is not
11520        // part of oldCodePath
11521        if (oldCodePath != null) {
11522            String subStr = oldCodePath;
11523            // Drop the suffix right away
11524            if (suffix != null && subStr.endsWith(suffix)) {
11525                subStr = subStr.substring(0, subStr.length() - suffix.length());
11526            }
11527            // If oldCodePath already contains prefix find out the
11528            // ending index to either increment or decrement.
11529            int sidx = subStr.lastIndexOf(prefix);
11530            if (sidx != -1) {
11531                subStr = subStr.substring(sidx + prefix.length());
11532                if (subStr != null) {
11533                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11534                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11535                    }
11536                    try {
11537                        idx = Integer.parseInt(subStr);
11538                        if (idx <= 1) {
11539                            idx++;
11540                        } else {
11541                            idx--;
11542                        }
11543                    } catch(NumberFormatException e) {
11544                    }
11545                }
11546            }
11547        }
11548        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11549        return prefix + idxStr;
11550    }
11551
11552    private File getNextCodePath(File targetDir, String packageName) {
11553        int suffix = 1;
11554        File result;
11555        do {
11556            result = new File(targetDir, packageName + "-" + suffix);
11557            suffix++;
11558        } while (result.exists());
11559        return result;
11560    }
11561
11562    // Utility method that returns the relative package path with respect
11563    // to the installation directory. Like say for /data/data/com.test-1.apk
11564    // string com.test-1 is returned.
11565    static String deriveCodePathName(String codePath) {
11566        if (codePath == null) {
11567            return null;
11568        }
11569        final File codeFile = new File(codePath);
11570        final String name = codeFile.getName();
11571        if (codeFile.isDirectory()) {
11572            return name;
11573        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11574            final int lastDot = name.lastIndexOf('.');
11575            return name.substring(0, lastDot);
11576        } else {
11577            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11578            return null;
11579        }
11580    }
11581
11582    class PackageInstalledInfo {
11583        String name;
11584        int uid;
11585        // The set of users that originally had this package installed.
11586        int[] origUsers;
11587        // The set of users that now have this package installed.
11588        int[] newUsers;
11589        PackageParser.Package pkg;
11590        int returnCode;
11591        String returnMsg;
11592        PackageRemovedInfo removedInfo;
11593
11594        public void setError(int code, String msg) {
11595            returnCode = code;
11596            returnMsg = msg;
11597            Slog.w(TAG, msg);
11598        }
11599
11600        public void setError(String msg, PackageParserException e) {
11601            returnCode = e.error;
11602            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11603            Slog.w(TAG, msg, e);
11604        }
11605
11606        public void setError(String msg, PackageManagerException e) {
11607            returnCode = e.error;
11608            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11609            Slog.w(TAG, msg, e);
11610        }
11611
11612        // In some error cases we want to convey more info back to the observer
11613        String origPackage;
11614        String origPermission;
11615    }
11616
11617    /*
11618     * Install a non-existing package.
11619     */
11620    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11621            UserHandle user, String installerPackageName, String volumeUuid,
11622            PackageInstalledInfo res) {
11623        // Remember this for later, in case we need to rollback this install
11624        String pkgName = pkg.packageName;
11625
11626        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11627        final boolean dataDirExists = Environment
11628                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11629        synchronized(mPackages) {
11630            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11631                // A package with the same name is already installed, though
11632                // it has been renamed to an older name.  The package we
11633                // are trying to install should be installed as an update to
11634                // the existing one, but that has not been requested, so bail.
11635                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11636                        + " without first uninstalling package running as "
11637                        + mSettings.mRenamedPackages.get(pkgName));
11638                return;
11639            }
11640            if (mPackages.containsKey(pkgName)) {
11641                // Don't allow installation over an existing package with the same name.
11642                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11643                        + " without first uninstalling.");
11644                return;
11645            }
11646        }
11647
11648        try {
11649            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11650                    System.currentTimeMillis(), user);
11651
11652            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11653            // delete the partially installed application. the data directory will have to be
11654            // restored if it was already existing
11655            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11656                // remove package from internal structures.  Note that we want deletePackageX to
11657                // delete the package data and cache directories that it created in
11658                // scanPackageLocked, unless those directories existed before we even tried to
11659                // install.
11660                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11661                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11662                                res.removedInfo, true);
11663            }
11664
11665        } catch (PackageManagerException e) {
11666            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11667        }
11668    }
11669
11670    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11671        // Can't rotate keys during boot or if sharedUser.
11672        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11673                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11674            return false;
11675        }
11676        // app is using upgradeKeySets; make sure all are valid
11677        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11678        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11679        for (int i = 0; i < upgradeKeySets.length; i++) {
11680            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11681                Slog.wtf(TAG, "Package "
11682                         + (oldPs.name != null ? oldPs.name : "<null>")
11683                         + " contains upgrade-key-set reference to unknown key-set: "
11684                         + upgradeKeySets[i]
11685                         + " reverting to signatures check.");
11686                return false;
11687            }
11688        }
11689        return true;
11690    }
11691
11692    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11693        // Upgrade keysets are being used.  Determine if new package has a superset of the
11694        // required keys.
11695        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11696        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11697        for (int i = 0; i < upgradeKeySets.length; i++) {
11698            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11699            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11700                return true;
11701            }
11702        }
11703        return false;
11704    }
11705
11706    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11707            UserHandle user, String installerPackageName, String volumeUuid,
11708            PackageInstalledInfo res) {
11709        final PackageParser.Package oldPackage;
11710        final String pkgName = pkg.packageName;
11711        final int[] allUsers;
11712        final boolean[] perUserInstalled;
11713        final boolean weFroze;
11714
11715        // First find the old package info and check signatures
11716        synchronized(mPackages) {
11717            oldPackage = mPackages.get(pkgName);
11718            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11719            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11720            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11721                if(!checkUpgradeKeySetLP(ps, pkg)) {
11722                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11723                            "New package not signed by keys specified by upgrade-keysets: "
11724                            + pkgName);
11725                    return;
11726                }
11727            } else {
11728                // default to original signature matching
11729                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11730                    != PackageManager.SIGNATURE_MATCH) {
11731                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11732                            "New package has a different signature: " + pkgName);
11733                    return;
11734                }
11735            }
11736
11737            // In case of rollback, remember per-user/profile install state
11738            allUsers = sUserManager.getUserIds();
11739            perUserInstalled = new boolean[allUsers.length];
11740            for (int i = 0; i < allUsers.length; i++) {
11741                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11742            }
11743
11744            // Mark the app as frozen to prevent launching during the upgrade
11745            // process, and then kill all running instances
11746            if (!ps.frozen) {
11747                ps.frozen = true;
11748                weFroze = true;
11749            } else {
11750                weFroze = false;
11751            }
11752        }
11753
11754        // Now that we're guarded by frozen state, kill app during upgrade
11755        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11756
11757        try {
11758            boolean sysPkg = (isSystemApp(oldPackage));
11759            if (sysPkg) {
11760                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11761                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11762            } else {
11763                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11764                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11765            }
11766        } finally {
11767            // Regardless of success or failure of upgrade steps above, always
11768            // unfreeze the package if we froze it
11769            if (weFroze) {
11770                unfreezePackage(pkgName);
11771            }
11772        }
11773    }
11774
11775    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11776            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11777            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11778            String volumeUuid, PackageInstalledInfo res) {
11779        String pkgName = deletedPackage.packageName;
11780        boolean deletedPkg = true;
11781        boolean updatedSettings = false;
11782
11783        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11784                + deletedPackage);
11785        long origUpdateTime;
11786        if (pkg.mExtras != null) {
11787            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11788        } else {
11789            origUpdateTime = 0;
11790        }
11791
11792        // First delete the existing package while retaining the data directory
11793        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11794                res.removedInfo, true)) {
11795            // If the existing package wasn't successfully deleted
11796            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11797            deletedPkg = false;
11798        } else {
11799            // Successfully deleted the old package; proceed with replace.
11800
11801            // If deleted package lived in a container, give users a chance to
11802            // relinquish resources before killing.
11803            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11804                if (DEBUG_INSTALL) {
11805                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11806                }
11807                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11808                final ArrayList<String> pkgList = new ArrayList<String>(1);
11809                pkgList.add(deletedPackage.applicationInfo.packageName);
11810                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11811            }
11812
11813            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11814            try {
11815                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11816                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11817                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11818                        perUserInstalled, res, user);
11819                updatedSettings = true;
11820            } catch (PackageManagerException e) {
11821                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11822            }
11823        }
11824
11825        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11826            // remove package from internal structures.  Note that we want deletePackageX to
11827            // delete the package data and cache directories that it created in
11828            // scanPackageLocked, unless those directories existed before we even tried to
11829            // install.
11830            if(updatedSettings) {
11831                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11832                deletePackageLI(
11833                        pkgName, null, true, allUsers, perUserInstalled,
11834                        PackageManager.DELETE_KEEP_DATA,
11835                                res.removedInfo, true);
11836            }
11837            // Since we failed to install the new package we need to restore the old
11838            // package that we deleted.
11839            if (deletedPkg) {
11840                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11841                File restoreFile = new File(deletedPackage.codePath);
11842                // Parse old package
11843                boolean oldExternal = isExternal(deletedPackage);
11844                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11845                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11846                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11847                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11848                try {
11849                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11850                } catch (PackageManagerException e) {
11851                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11852                            + e.getMessage());
11853                    return;
11854                }
11855                // Restore of old package succeeded. Update permissions.
11856                // writer
11857                synchronized (mPackages) {
11858                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11859                            UPDATE_PERMISSIONS_ALL);
11860                    // can downgrade to reader
11861                    mSettings.writeLPr();
11862                }
11863                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11864            }
11865        }
11866    }
11867
11868    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11869            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11870            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11871            String volumeUuid, PackageInstalledInfo res) {
11872        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11873                + ", old=" + deletedPackage);
11874        boolean disabledSystem = false;
11875        boolean updatedSettings = false;
11876        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11877        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11878                != 0) {
11879            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11880        }
11881        String packageName = deletedPackage.packageName;
11882        if (packageName == null) {
11883            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11884                    "Attempt to delete null packageName.");
11885            return;
11886        }
11887        PackageParser.Package oldPkg;
11888        PackageSetting oldPkgSetting;
11889        // reader
11890        synchronized (mPackages) {
11891            oldPkg = mPackages.get(packageName);
11892            oldPkgSetting = mSettings.mPackages.get(packageName);
11893            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11894                    (oldPkgSetting == null)) {
11895                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11896                        "Couldn't find package:" + packageName + " information");
11897                return;
11898            }
11899        }
11900
11901        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11902        res.removedInfo.removedPackage = packageName;
11903        // Remove existing system package
11904        removePackageLI(oldPkgSetting, true);
11905        // writer
11906        synchronized (mPackages) {
11907            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11908            if (!disabledSystem && deletedPackage != null) {
11909                // We didn't need to disable the .apk as a current system package,
11910                // which means we are replacing another update that is already
11911                // installed.  We need to make sure to delete the older one's .apk.
11912                res.removedInfo.args = createInstallArgsForExisting(0,
11913                        deletedPackage.applicationInfo.getCodePath(),
11914                        deletedPackage.applicationInfo.getResourcePath(),
11915                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11916            } else {
11917                res.removedInfo.args = null;
11918            }
11919        }
11920
11921        // Successfully disabled the old package. Now proceed with re-installation
11922        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11923
11924        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11925        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11926
11927        PackageParser.Package newPackage = null;
11928        try {
11929            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11930            if (newPackage.mExtras != null) {
11931                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11932                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11933                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11934
11935                // is the update attempting to change shared user? that isn't going to work...
11936                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11937                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11938                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11939                            + " to " + newPkgSetting.sharedUser);
11940                    updatedSettings = true;
11941                }
11942            }
11943
11944            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11945                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11946                        perUserInstalled, res, user);
11947                updatedSettings = true;
11948            }
11949
11950        } catch (PackageManagerException e) {
11951            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11952        }
11953
11954        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11955            // Re installation failed. Restore old information
11956            // Remove new pkg information
11957            if (newPackage != null) {
11958                removeInstalledPackageLI(newPackage, true);
11959            }
11960            // Add back the old system package
11961            try {
11962                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11963            } catch (PackageManagerException e) {
11964                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11965            }
11966            // Restore the old system information in Settings
11967            synchronized (mPackages) {
11968                if (disabledSystem) {
11969                    mSettings.enableSystemPackageLPw(packageName);
11970                }
11971                if (updatedSettings) {
11972                    mSettings.setInstallerPackageName(packageName,
11973                            oldPkgSetting.installerPackageName);
11974                }
11975                mSettings.writeLPr();
11976            }
11977        }
11978    }
11979
11980    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11981            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11982            UserHandle user) {
11983        String pkgName = newPackage.packageName;
11984        synchronized (mPackages) {
11985            //write settings. the installStatus will be incomplete at this stage.
11986            //note that the new package setting would have already been
11987            //added to mPackages. It hasn't been persisted yet.
11988            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11989            mSettings.writeLPr();
11990        }
11991
11992        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11993
11994        synchronized (mPackages) {
11995            updatePermissionsLPw(newPackage.packageName, newPackage,
11996                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11997                            ? UPDATE_PERMISSIONS_ALL : 0));
11998            // For system-bundled packages, we assume that installing an upgraded version
11999            // of the package implies that the user actually wants to run that new code,
12000            // so we enable the package.
12001            PackageSetting ps = mSettings.mPackages.get(pkgName);
12002            if (ps != null) {
12003                if (isSystemApp(newPackage)) {
12004                    // NB: implicit assumption that system package upgrades apply to all users
12005                    if (DEBUG_INSTALL) {
12006                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12007                    }
12008                    if (res.origUsers != null) {
12009                        for (int userHandle : res.origUsers) {
12010                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12011                                    userHandle, installerPackageName);
12012                        }
12013                    }
12014                    // Also convey the prior install/uninstall state
12015                    if (allUsers != null && perUserInstalled != null) {
12016                        for (int i = 0; i < allUsers.length; i++) {
12017                            if (DEBUG_INSTALL) {
12018                                Slog.d(TAG, "    user " + allUsers[i]
12019                                        + " => " + perUserInstalled[i]);
12020                            }
12021                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12022                        }
12023                        // these install state changes will be persisted in the
12024                        // upcoming call to mSettings.writeLPr().
12025                    }
12026                }
12027                // It's implied that when a user requests installation, they want the app to be
12028                // installed and enabled.
12029                int userId = user.getIdentifier();
12030                if (userId != UserHandle.USER_ALL) {
12031                    ps.setInstalled(true, userId);
12032                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12033                }
12034            }
12035            res.name = pkgName;
12036            res.uid = newPackage.applicationInfo.uid;
12037            res.pkg = newPackage;
12038            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12039            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12040            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12041            //to update install status
12042            mSettings.writeLPr();
12043        }
12044    }
12045
12046    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12047        final int installFlags = args.installFlags;
12048        final String installerPackageName = args.installerPackageName;
12049        final String volumeUuid = args.volumeUuid;
12050        final File tmpPackageFile = new File(args.getCodePath());
12051        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12052        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12053                || (args.volumeUuid != null));
12054        boolean replace = false;
12055        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12056        if (args.move != null) {
12057            // moving a complete application; perfom an initial scan on the new install location
12058            scanFlags |= SCAN_INITIAL;
12059        }
12060        // Result object to be returned
12061        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12062
12063        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12064        // Retrieve PackageSettings and parse package
12065        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12066                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12067                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12068        PackageParser pp = new PackageParser();
12069        pp.setSeparateProcesses(mSeparateProcesses);
12070        pp.setDisplayMetrics(mMetrics);
12071
12072        final PackageParser.Package pkg;
12073        try {
12074            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12075        } catch (PackageParserException e) {
12076            res.setError("Failed parse during installPackageLI", e);
12077            return;
12078        }
12079
12080        // Mark that we have an install time CPU ABI override.
12081        pkg.cpuAbiOverride = args.abiOverride;
12082
12083        String pkgName = res.name = pkg.packageName;
12084        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12085            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12086                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12087                return;
12088            }
12089        }
12090
12091        try {
12092            pp.collectCertificates(pkg, parseFlags);
12093            pp.collectManifestDigest(pkg);
12094        } catch (PackageParserException e) {
12095            res.setError("Failed collect during installPackageLI", e);
12096            return;
12097        }
12098
12099        /* If the installer passed in a manifest digest, compare it now. */
12100        if (args.manifestDigest != null) {
12101            if (DEBUG_INSTALL) {
12102                final String parsedManifest = pkg.manifestDigest == null ? "null"
12103                        : pkg.manifestDigest.toString();
12104                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12105                        + parsedManifest);
12106            }
12107
12108            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12109                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12110                return;
12111            }
12112        } else if (DEBUG_INSTALL) {
12113            final String parsedManifest = pkg.manifestDigest == null
12114                    ? "null" : pkg.manifestDigest.toString();
12115            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12116        }
12117
12118        // Get rid of all references to package scan path via parser.
12119        pp = null;
12120        String oldCodePath = null;
12121        boolean systemApp = false;
12122        synchronized (mPackages) {
12123            // Check if installing already existing package
12124            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12125                String oldName = mSettings.mRenamedPackages.get(pkgName);
12126                if (pkg.mOriginalPackages != null
12127                        && pkg.mOriginalPackages.contains(oldName)
12128                        && mPackages.containsKey(oldName)) {
12129                    // This package is derived from an original package,
12130                    // and this device has been updating from that original
12131                    // name.  We must continue using the original name, so
12132                    // rename the new package here.
12133                    pkg.setPackageName(oldName);
12134                    pkgName = pkg.packageName;
12135                    replace = true;
12136                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12137                            + oldName + " pkgName=" + pkgName);
12138                } else if (mPackages.containsKey(pkgName)) {
12139                    // This package, under its official name, already exists
12140                    // on the device; we should replace it.
12141                    replace = true;
12142                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12143                }
12144
12145                // Prevent apps opting out from runtime permissions
12146                if (replace) {
12147                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12148                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12149                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12150                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12151                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12152                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12153                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12154                                        + " doesn't support runtime permissions but the old"
12155                                        + " target SDK " + oldTargetSdk + " does.");
12156                        return;
12157                    }
12158                }
12159            }
12160
12161            PackageSetting ps = mSettings.mPackages.get(pkgName);
12162            if (ps != null) {
12163                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12164
12165                // Quick sanity check that we're signed correctly if updating;
12166                // we'll check this again later when scanning, but we want to
12167                // bail early here before tripping over redefined permissions.
12168                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12169                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12170                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12171                                + pkg.packageName + " upgrade keys do not match the "
12172                                + "previously installed version");
12173                        return;
12174                    }
12175                } else {
12176                    try {
12177                        verifySignaturesLP(ps, pkg);
12178                    } catch (PackageManagerException e) {
12179                        res.setError(e.error, e.getMessage());
12180                        return;
12181                    }
12182                }
12183
12184                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12185                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12186                    systemApp = (ps.pkg.applicationInfo.flags &
12187                            ApplicationInfo.FLAG_SYSTEM) != 0;
12188                }
12189                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12190            }
12191
12192            // Check whether the newly-scanned package wants to define an already-defined perm
12193            int N = pkg.permissions.size();
12194            for (int i = N-1; i >= 0; i--) {
12195                PackageParser.Permission perm = pkg.permissions.get(i);
12196                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12197                if (bp != null) {
12198                    // If the defining package is signed with our cert, it's okay.  This
12199                    // also includes the "updating the same package" case, of course.
12200                    // "updating same package" could also involve key-rotation.
12201                    final boolean sigsOk;
12202                    if (bp.sourcePackage.equals(pkg.packageName)
12203                            && (bp.packageSetting instanceof PackageSetting)
12204                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12205                                    scanFlags))) {
12206                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12207                    } else {
12208                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12209                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12210                    }
12211                    if (!sigsOk) {
12212                        // If the owning package is the system itself, we log but allow
12213                        // install to proceed; we fail the install on all other permission
12214                        // redefinitions.
12215                        if (!bp.sourcePackage.equals("android")) {
12216                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12217                                    + pkg.packageName + " attempting to redeclare permission "
12218                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12219                            res.origPermission = perm.info.name;
12220                            res.origPackage = bp.sourcePackage;
12221                            return;
12222                        } else {
12223                            Slog.w(TAG, "Package " + pkg.packageName
12224                                    + " attempting to redeclare system permission "
12225                                    + perm.info.name + "; ignoring new declaration");
12226                            pkg.permissions.remove(i);
12227                        }
12228                    }
12229                }
12230            }
12231
12232        }
12233
12234        if (systemApp && onExternal) {
12235            // Disable updates to system apps on sdcard
12236            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12237                    "Cannot install updates to system apps on sdcard");
12238            return;
12239        }
12240
12241        if (args.move != null) {
12242            // We did an in-place move, so dex is ready to roll
12243            scanFlags |= SCAN_NO_DEX;
12244            scanFlags |= SCAN_MOVE;
12245        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12246            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12247            scanFlags |= SCAN_NO_DEX;
12248
12249            try {
12250                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12251                        true /* extract libs */);
12252            } catch (PackageManagerException pme) {
12253                Slog.e(TAG, "Error deriving application ABI", pme);
12254                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12255                return;
12256            }
12257
12258            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12259            int result = mPackageDexOptimizer
12260                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12261                            false /* defer */, false /* inclDependencies */);
12262            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12263                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12264                return;
12265            }
12266        }
12267
12268        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12269            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12270            return;
12271        }
12272
12273        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12274
12275        if (replace) {
12276            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12277                    installerPackageName, volumeUuid, res);
12278        } else {
12279            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12280                    args.user, installerPackageName, volumeUuid, res);
12281        }
12282        synchronized (mPackages) {
12283            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12284            if (ps != null) {
12285                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12286            }
12287        }
12288    }
12289
12290    private void startIntentFilterVerifications(int userId, boolean replacing,
12291            PackageParser.Package pkg) {
12292        if (mIntentFilterVerifierComponent == null) {
12293            Slog.w(TAG, "No IntentFilter verification will not be done as "
12294                    + "there is no IntentFilterVerifier available!");
12295            return;
12296        }
12297
12298        final int verifierUid = getPackageUid(
12299                mIntentFilterVerifierComponent.getPackageName(),
12300                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12301
12302        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12303        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12304        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12305        mHandler.sendMessage(msg);
12306    }
12307
12308    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12309            PackageParser.Package pkg) {
12310        int size = pkg.activities.size();
12311        if (size == 0) {
12312            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12313                    "No activity, so no need to verify any IntentFilter!");
12314            return;
12315        }
12316
12317        final boolean hasDomainURLs = hasDomainURLs(pkg);
12318        if (!hasDomainURLs) {
12319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12320                    "No domain URLs, so no need to verify any IntentFilter!");
12321            return;
12322        }
12323
12324        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12325                + " if any IntentFilter from the " + size
12326                + " Activities needs verification ...");
12327
12328        int count = 0;
12329        final String packageName = pkg.packageName;
12330
12331        synchronized (mPackages) {
12332            // If this is a new install and we see that we've already run verification for this
12333            // package, we have nothing to do: it means the state was restored from backup.
12334            if (!replacing) {
12335                IntentFilterVerificationInfo ivi =
12336                        mSettings.getIntentFilterVerificationLPr(packageName);
12337                if (ivi != null) {
12338                    if (DEBUG_DOMAIN_VERIFICATION) {
12339                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12340                                + ivi.getStatusString());
12341                    }
12342                    return;
12343                }
12344            }
12345
12346            // If any filters need to be verified, then all need to be.
12347            boolean needToVerify = false;
12348            for (PackageParser.Activity a : pkg.activities) {
12349                for (ActivityIntentInfo filter : a.intents) {
12350                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12351                        if (DEBUG_DOMAIN_VERIFICATION) {
12352                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12353                        }
12354                        needToVerify = true;
12355                        break;
12356                    }
12357                }
12358            }
12359
12360            if (needToVerify) {
12361                final int verificationId = mIntentFilterVerificationToken++;
12362                for (PackageParser.Activity a : pkg.activities) {
12363                    for (ActivityIntentInfo filter : a.intents) {
12364                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12365                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12366                                    "Verification needed for IntentFilter:" + filter.toString());
12367                            mIntentFilterVerifier.addOneIntentFilterVerification(
12368                                    verifierUid, userId, verificationId, filter, packageName);
12369                            count++;
12370                        }
12371                    }
12372                }
12373            }
12374        }
12375
12376        if (count > 0) {
12377            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12378                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12379                    +  " for userId:" + userId);
12380            mIntentFilterVerifier.startVerifications(userId);
12381        } else {
12382            if (DEBUG_DOMAIN_VERIFICATION) {
12383                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12384            }
12385        }
12386    }
12387
12388    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12389        final ComponentName cn  = filter.activity.getComponentName();
12390        final String packageName = cn.getPackageName();
12391
12392        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12393                packageName);
12394        if (ivi == null) {
12395            return true;
12396        }
12397        int status = ivi.getStatus();
12398        switch (status) {
12399            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12400            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12401                return true;
12402
12403            default:
12404                // Nothing to do
12405                return false;
12406        }
12407    }
12408
12409    private static boolean isMultiArch(PackageSetting ps) {
12410        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12411    }
12412
12413    private static boolean isMultiArch(ApplicationInfo info) {
12414        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12415    }
12416
12417    private static boolean isExternal(PackageParser.Package pkg) {
12418        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12419    }
12420
12421    private static boolean isExternal(PackageSetting ps) {
12422        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12423    }
12424
12425    private static boolean isExternal(ApplicationInfo info) {
12426        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12427    }
12428
12429    private static boolean isSystemApp(PackageParser.Package pkg) {
12430        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12431    }
12432
12433    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12434        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12435    }
12436
12437    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12438        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12439    }
12440
12441    private static boolean isSystemApp(PackageSetting ps) {
12442        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12443    }
12444
12445    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12446        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12447    }
12448
12449    private int packageFlagsToInstallFlags(PackageSetting ps) {
12450        int installFlags = 0;
12451        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12452            // This existing package was an external ASEC install when we have
12453            // the external flag without a UUID
12454            installFlags |= PackageManager.INSTALL_EXTERNAL;
12455        }
12456        if (ps.isForwardLocked()) {
12457            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12458        }
12459        return installFlags;
12460    }
12461
12462    private void deleteTempPackageFiles() {
12463        final FilenameFilter filter = new FilenameFilter() {
12464            public boolean accept(File dir, String name) {
12465                return name.startsWith("vmdl") && name.endsWith(".tmp");
12466            }
12467        };
12468        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12469            file.delete();
12470        }
12471    }
12472
12473    @Override
12474    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12475            int flags) {
12476        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12477                flags);
12478    }
12479
12480    @Override
12481    public void deletePackage(final String packageName,
12482            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12483        mContext.enforceCallingOrSelfPermission(
12484                android.Manifest.permission.DELETE_PACKAGES, null);
12485        Preconditions.checkNotNull(packageName);
12486        Preconditions.checkNotNull(observer);
12487        final int uid = Binder.getCallingUid();
12488        if (UserHandle.getUserId(uid) != userId) {
12489            mContext.enforceCallingPermission(
12490                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12491                    "deletePackage for user " + userId);
12492        }
12493        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12494            try {
12495                observer.onPackageDeleted(packageName,
12496                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12497            } catch (RemoteException re) {
12498            }
12499            return;
12500        }
12501
12502        boolean uninstallBlocked = false;
12503        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12504            int[] users = sUserManager.getUserIds();
12505            for (int i = 0; i < users.length; ++i) {
12506                if (getBlockUninstallForUser(packageName, users[i])) {
12507                    uninstallBlocked = true;
12508                    break;
12509                }
12510            }
12511        } else {
12512            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12513        }
12514        if (uninstallBlocked) {
12515            try {
12516                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12517                        null);
12518            } catch (RemoteException re) {
12519            }
12520            return;
12521        }
12522
12523        if (DEBUG_REMOVE) {
12524            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12525        }
12526        // Queue up an async operation since the package deletion may take a little while.
12527        mHandler.post(new Runnable() {
12528            public void run() {
12529                mHandler.removeCallbacks(this);
12530                final int returnCode = deletePackageX(packageName, userId, flags);
12531                if (observer != null) {
12532                    try {
12533                        observer.onPackageDeleted(packageName, returnCode, null);
12534                    } catch (RemoteException e) {
12535                        Log.i(TAG, "Observer no longer exists.");
12536                    } //end catch
12537                } //end if
12538            } //end run
12539        });
12540    }
12541
12542    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12543        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12544                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12545        try {
12546            if (dpm != null) {
12547                if (dpm.isDeviceOwner(packageName)) {
12548                    return true;
12549                }
12550                int[] users;
12551                if (userId == UserHandle.USER_ALL) {
12552                    users = sUserManager.getUserIds();
12553                } else {
12554                    users = new int[]{userId};
12555                }
12556                for (int i = 0; i < users.length; ++i) {
12557                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12558                        return true;
12559                    }
12560                }
12561            }
12562        } catch (RemoteException e) {
12563        }
12564        return false;
12565    }
12566
12567    /**
12568     *  This method is an internal method that could be get invoked either
12569     *  to delete an installed package or to clean up a failed installation.
12570     *  After deleting an installed package, a broadcast is sent to notify any
12571     *  listeners that the package has been installed. For cleaning up a failed
12572     *  installation, the broadcast is not necessary since the package's
12573     *  installation wouldn't have sent the initial broadcast either
12574     *  The key steps in deleting a package are
12575     *  deleting the package information in internal structures like mPackages,
12576     *  deleting the packages base directories through installd
12577     *  updating mSettings to reflect current status
12578     *  persisting settings for later use
12579     *  sending a broadcast if necessary
12580     */
12581    private int deletePackageX(String packageName, int userId, int flags) {
12582        final PackageRemovedInfo info = new PackageRemovedInfo();
12583        final boolean res;
12584
12585        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12586                ? UserHandle.ALL : new UserHandle(userId);
12587
12588        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12589            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12590            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12591        }
12592
12593        boolean removedForAllUsers = false;
12594        boolean systemUpdate = false;
12595
12596        // for the uninstall-updates case and restricted profiles, remember the per-
12597        // userhandle installed state
12598        int[] allUsers;
12599        boolean[] perUserInstalled;
12600        synchronized (mPackages) {
12601            PackageSetting ps = mSettings.mPackages.get(packageName);
12602            allUsers = sUserManager.getUserIds();
12603            perUserInstalled = new boolean[allUsers.length];
12604            for (int i = 0; i < allUsers.length; i++) {
12605                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12606            }
12607        }
12608
12609        synchronized (mInstallLock) {
12610            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12611            res = deletePackageLI(packageName, removeForUser,
12612                    true, allUsers, perUserInstalled,
12613                    flags | REMOVE_CHATTY, info, true);
12614            systemUpdate = info.isRemovedPackageSystemUpdate;
12615            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12616                removedForAllUsers = true;
12617            }
12618            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12619                    + " removedForAllUsers=" + removedForAllUsers);
12620        }
12621
12622        if (res) {
12623            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12624
12625            // If the removed package was a system update, the old system package
12626            // was re-enabled; we need to broadcast this information
12627            if (systemUpdate) {
12628                Bundle extras = new Bundle(1);
12629                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12630                        ? info.removedAppId : info.uid);
12631                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12632
12633                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12634                        extras, null, null, null);
12635                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12636                        extras, null, null, null);
12637                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12638                        null, packageName, null, null);
12639            }
12640        }
12641        // Force a gc here.
12642        Runtime.getRuntime().gc();
12643        // Delete the resources here after sending the broadcast to let
12644        // other processes clean up before deleting resources.
12645        if (info.args != null) {
12646            synchronized (mInstallLock) {
12647                info.args.doPostDeleteLI(true);
12648            }
12649        }
12650
12651        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12652    }
12653
12654    class PackageRemovedInfo {
12655        String removedPackage;
12656        int uid = -1;
12657        int removedAppId = -1;
12658        int[] removedUsers = null;
12659        boolean isRemovedPackageSystemUpdate = false;
12660        // Clean up resources deleted packages.
12661        InstallArgs args = null;
12662
12663        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12664            Bundle extras = new Bundle(1);
12665            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12666            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12667            if (replacing) {
12668                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12669            }
12670            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12671            if (removedPackage != null) {
12672                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12673                        extras, null, null, removedUsers);
12674                if (fullRemove && !replacing) {
12675                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12676                            extras, null, null, removedUsers);
12677                }
12678            }
12679            if (removedAppId >= 0) {
12680                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12681                        removedUsers);
12682            }
12683        }
12684    }
12685
12686    /*
12687     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12688     * flag is not set, the data directory is removed as well.
12689     * make sure this flag is set for partially installed apps. If not its meaningless to
12690     * delete a partially installed application.
12691     */
12692    private void removePackageDataLI(PackageSetting ps,
12693            int[] allUserHandles, boolean[] perUserInstalled,
12694            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12695        String packageName = ps.name;
12696        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12697        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12698        // Retrieve object to delete permissions for shared user later on
12699        final PackageSetting deletedPs;
12700        // reader
12701        synchronized (mPackages) {
12702            deletedPs = mSettings.mPackages.get(packageName);
12703            if (outInfo != null) {
12704                outInfo.removedPackage = packageName;
12705                outInfo.removedUsers = deletedPs != null
12706                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12707                        : null;
12708            }
12709        }
12710        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12711            removeDataDirsLI(ps.volumeUuid, packageName);
12712            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12713        }
12714        // writer
12715        synchronized (mPackages) {
12716            if (deletedPs != null) {
12717                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12718                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12719                    clearDefaultBrowserIfNeeded(packageName);
12720                    if (outInfo != null) {
12721                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12722                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12723                    }
12724                    updatePermissionsLPw(deletedPs.name, null, 0);
12725                    if (deletedPs.sharedUser != null) {
12726                        // Remove permissions associated with package. Since runtime
12727                        // permissions are per user we have to kill the removed package
12728                        // or packages running under the shared user of the removed
12729                        // package if revoking the permissions requested only by the removed
12730                        // package is successful and this causes a change in gids.
12731                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12732                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12733                                    userId);
12734                            if (userIdToKill == UserHandle.USER_ALL
12735                                    || userIdToKill >= UserHandle.USER_OWNER) {
12736                                // If gids changed for this user, kill all affected packages.
12737                                mHandler.post(new Runnable() {
12738                                    @Override
12739                                    public void run() {
12740                                        // This has to happen with no lock held.
12741                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12742                                                KILL_APP_REASON_GIDS_CHANGED);
12743                                    }
12744                                });
12745                                break;
12746                            }
12747                        }
12748                    }
12749                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12750                }
12751                // make sure to preserve per-user disabled state if this removal was just
12752                // a downgrade of a system app to the factory package
12753                if (allUserHandles != null && perUserInstalled != null) {
12754                    if (DEBUG_REMOVE) {
12755                        Slog.d(TAG, "Propagating install state across downgrade");
12756                    }
12757                    for (int i = 0; i < allUserHandles.length; i++) {
12758                        if (DEBUG_REMOVE) {
12759                            Slog.d(TAG, "    user " + allUserHandles[i]
12760                                    + " => " + perUserInstalled[i]);
12761                        }
12762                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12763                    }
12764                }
12765            }
12766            // can downgrade to reader
12767            if (writeSettings) {
12768                // Save settings now
12769                mSettings.writeLPr();
12770            }
12771        }
12772        if (outInfo != null) {
12773            // A user ID was deleted here. Go through all users and remove it
12774            // from KeyStore.
12775            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12776        }
12777    }
12778
12779    static boolean locationIsPrivileged(File path) {
12780        try {
12781            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12782                    .getCanonicalPath();
12783            return path.getCanonicalPath().startsWith(privilegedAppDir);
12784        } catch (IOException e) {
12785            Slog.e(TAG, "Unable to access code path " + path);
12786        }
12787        return false;
12788    }
12789
12790    /*
12791     * Tries to delete system package.
12792     */
12793    private boolean deleteSystemPackageLI(PackageSetting newPs,
12794            int[] allUserHandles, boolean[] perUserInstalled,
12795            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12796        final boolean applyUserRestrictions
12797                = (allUserHandles != null) && (perUserInstalled != null);
12798        PackageSetting disabledPs = null;
12799        // Confirm if the system package has been updated
12800        // An updated system app can be deleted. This will also have to restore
12801        // the system pkg from system partition
12802        // reader
12803        synchronized (mPackages) {
12804            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12805        }
12806        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12807                + " disabledPs=" + disabledPs);
12808        if (disabledPs == null) {
12809            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12810            return false;
12811        } else if (DEBUG_REMOVE) {
12812            Slog.d(TAG, "Deleting system pkg from data partition");
12813        }
12814        if (DEBUG_REMOVE) {
12815            if (applyUserRestrictions) {
12816                Slog.d(TAG, "Remembering install states:");
12817                for (int i = 0; i < allUserHandles.length; i++) {
12818                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12819                }
12820            }
12821        }
12822        // Delete the updated package
12823        outInfo.isRemovedPackageSystemUpdate = true;
12824        if (disabledPs.versionCode < newPs.versionCode) {
12825            // Delete data for downgrades
12826            flags &= ~PackageManager.DELETE_KEEP_DATA;
12827        } else {
12828            // Preserve data by setting flag
12829            flags |= PackageManager.DELETE_KEEP_DATA;
12830        }
12831        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12832                allUserHandles, perUserInstalled, outInfo, writeSettings);
12833        if (!ret) {
12834            return false;
12835        }
12836        // writer
12837        synchronized (mPackages) {
12838            // Reinstate the old system package
12839            mSettings.enableSystemPackageLPw(newPs.name);
12840            // Remove any native libraries from the upgraded package.
12841            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12842        }
12843        // Install the system package
12844        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12845        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12846        if (locationIsPrivileged(disabledPs.codePath)) {
12847            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12848        }
12849
12850        final PackageParser.Package newPkg;
12851        try {
12852            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12853        } catch (PackageManagerException e) {
12854            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12855            return false;
12856        }
12857
12858        // writer
12859        synchronized (mPackages) {
12860            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12861
12862            // Propagate the permissions state as we do want to drop on the floor
12863            // runtime permissions. The update permissions method below will take
12864            // care of removing obsolete permissions and grant install permissions.
12865            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12866            updatePermissionsLPw(newPkg.packageName, newPkg,
12867                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12868
12869            if (applyUserRestrictions) {
12870                if (DEBUG_REMOVE) {
12871                    Slog.d(TAG, "Propagating install state across reinstall");
12872                }
12873                for (int i = 0; i < allUserHandles.length; i++) {
12874                    if (DEBUG_REMOVE) {
12875                        Slog.d(TAG, "    user " + allUserHandles[i]
12876                                + " => " + perUserInstalled[i]);
12877                    }
12878                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12879                }
12880                // Regardless of writeSettings we need to ensure that this restriction
12881                // state propagation is persisted
12882                mSettings.writeAllUsersPackageRestrictionsLPr();
12883            }
12884            // can downgrade to reader here
12885            if (writeSettings) {
12886                mSettings.writeLPr();
12887            }
12888        }
12889        return true;
12890    }
12891
12892    private boolean deleteInstalledPackageLI(PackageSetting ps,
12893            boolean deleteCodeAndResources, int flags,
12894            int[] allUserHandles, boolean[] perUserInstalled,
12895            PackageRemovedInfo outInfo, boolean writeSettings) {
12896        if (outInfo != null) {
12897            outInfo.uid = ps.appId;
12898        }
12899
12900        // Delete package data from internal structures and also remove data if flag is set
12901        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12902
12903        // Delete application code and resources
12904        if (deleteCodeAndResources && (outInfo != null)) {
12905            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12906                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12907            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12908        }
12909        return true;
12910    }
12911
12912    @Override
12913    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12914            int userId) {
12915        mContext.enforceCallingOrSelfPermission(
12916                android.Manifest.permission.DELETE_PACKAGES, null);
12917        synchronized (mPackages) {
12918            PackageSetting ps = mSettings.mPackages.get(packageName);
12919            if (ps == null) {
12920                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12921                return false;
12922            }
12923            if (!ps.getInstalled(userId)) {
12924                // Can't block uninstall for an app that is not installed or enabled.
12925                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12926                return false;
12927            }
12928            ps.setBlockUninstall(blockUninstall, userId);
12929            mSettings.writePackageRestrictionsLPr(userId);
12930        }
12931        return true;
12932    }
12933
12934    @Override
12935    public boolean getBlockUninstallForUser(String packageName, int userId) {
12936        synchronized (mPackages) {
12937            PackageSetting ps = mSettings.mPackages.get(packageName);
12938            if (ps == null) {
12939                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12940                return false;
12941            }
12942            return ps.getBlockUninstall(userId);
12943        }
12944    }
12945
12946    /*
12947     * This method handles package deletion in general
12948     */
12949    private boolean deletePackageLI(String packageName, UserHandle user,
12950            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12951            int flags, PackageRemovedInfo outInfo,
12952            boolean writeSettings) {
12953        if (packageName == null) {
12954            Slog.w(TAG, "Attempt to delete null packageName.");
12955            return false;
12956        }
12957        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12958        PackageSetting ps;
12959        boolean dataOnly = false;
12960        int removeUser = -1;
12961        int appId = -1;
12962        synchronized (mPackages) {
12963            ps = mSettings.mPackages.get(packageName);
12964            if (ps == null) {
12965                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12966                return false;
12967            }
12968            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12969                    && user.getIdentifier() != UserHandle.USER_ALL) {
12970                // The caller is asking that the package only be deleted for a single
12971                // user.  To do this, we just mark its uninstalled state and delete
12972                // its data.  If this is a system app, we only allow this to happen if
12973                // they have set the special DELETE_SYSTEM_APP which requests different
12974                // semantics than normal for uninstalling system apps.
12975                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12976                ps.setUserState(user.getIdentifier(),
12977                        COMPONENT_ENABLED_STATE_DEFAULT,
12978                        false, //installed
12979                        true,  //stopped
12980                        true,  //notLaunched
12981                        false, //hidden
12982                        null, null, null,
12983                        false, // blockUninstall
12984                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
12985                if (!isSystemApp(ps)) {
12986                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12987                        // Other user still have this package installed, so all
12988                        // we need to do is clear this user's data and save that
12989                        // it is uninstalled.
12990                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12991                        removeUser = user.getIdentifier();
12992                        appId = ps.appId;
12993                        scheduleWritePackageRestrictionsLocked(removeUser);
12994                    } else {
12995                        // We need to set it back to 'installed' so the uninstall
12996                        // broadcasts will be sent correctly.
12997                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12998                        ps.setInstalled(true, user.getIdentifier());
12999                    }
13000                } else {
13001                    // This is a system app, so we assume that the
13002                    // other users still have this package installed, so all
13003                    // we need to do is clear this user's data and save that
13004                    // it is uninstalled.
13005                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13006                    removeUser = user.getIdentifier();
13007                    appId = ps.appId;
13008                    scheduleWritePackageRestrictionsLocked(removeUser);
13009                }
13010            }
13011        }
13012
13013        if (removeUser >= 0) {
13014            // From above, we determined that we are deleting this only
13015            // for a single user.  Continue the work here.
13016            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13017            if (outInfo != null) {
13018                outInfo.removedPackage = packageName;
13019                outInfo.removedAppId = appId;
13020                outInfo.removedUsers = new int[] {removeUser};
13021            }
13022            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13023            removeKeystoreDataIfNeeded(removeUser, appId);
13024            schedulePackageCleaning(packageName, removeUser, false);
13025            synchronized (mPackages) {
13026                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13027                    scheduleWritePackageRestrictionsLocked(removeUser);
13028                }
13029                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13030            }
13031            return true;
13032        }
13033
13034        if (dataOnly) {
13035            // Delete application data first
13036            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13037            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13038            return true;
13039        }
13040
13041        boolean ret = false;
13042        if (isSystemApp(ps)) {
13043            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13044            // When an updated system application is deleted we delete the existing resources as well and
13045            // fall back to existing code in system partition
13046            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13047                    flags, outInfo, writeSettings);
13048        } else {
13049            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13050            // Kill application pre-emptively especially for apps on sd.
13051            killApplication(packageName, ps.appId, "uninstall pkg");
13052            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13053                    allUserHandles, perUserInstalled,
13054                    outInfo, writeSettings);
13055        }
13056
13057        return ret;
13058    }
13059
13060    private final class ClearStorageConnection implements ServiceConnection {
13061        IMediaContainerService mContainerService;
13062
13063        @Override
13064        public void onServiceConnected(ComponentName name, IBinder service) {
13065            synchronized (this) {
13066                mContainerService = IMediaContainerService.Stub.asInterface(service);
13067                notifyAll();
13068            }
13069        }
13070
13071        @Override
13072        public void onServiceDisconnected(ComponentName name) {
13073        }
13074    }
13075
13076    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13077        final boolean mounted;
13078        if (Environment.isExternalStorageEmulated()) {
13079            mounted = true;
13080        } else {
13081            final String status = Environment.getExternalStorageState();
13082
13083            mounted = status.equals(Environment.MEDIA_MOUNTED)
13084                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13085        }
13086
13087        if (!mounted) {
13088            return;
13089        }
13090
13091        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13092        int[] users;
13093        if (userId == UserHandle.USER_ALL) {
13094            users = sUserManager.getUserIds();
13095        } else {
13096            users = new int[] { userId };
13097        }
13098        final ClearStorageConnection conn = new ClearStorageConnection();
13099        if (mContext.bindServiceAsUser(
13100                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13101            try {
13102                for (int curUser : users) {
13103                    long timeout = SystemClock.uptimeMillis() + 5000;
13104                    synchronized (conn) {
13105                        long now = SystemClock.uptimeMillis();
13106                        while (conn.mContainerService == null && now < timeout) {
13107                            try {
13108                                conn.wait(timeout - now);
13109                            } catch (InterruptedException e) {
13110                            }
13111                        }
13112                    }
13113                    if (conn.mContainerService == null) {
13114                        return;
13115                    }
13116
13117                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13118                    clearDirectory(conn.mContainerService,
13119                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13120                    if (allData) {
13121                        clearDirectory(conn.mContainerService,
13122                                userEnv.buildExternalStorageAppDataDirs(packageName));
13123                        clearDirectory(conn.mContainerService,
13124                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13125                    }
13126                }
13127            } finally {
13128                mContext.unbindService(conn);
13129            }
13130        }
13131    }
13132
13133    @Override
13134    public void clearApplicationUserData(final String packageName,
13135            final IPackageDataObserver observer, final int userId) {
13136        mContext.enforceCallingOrSelfPermission(
13137                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13138        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13139        // Queue up an async operation since the package deletion may take a little while.
13140        mHandler.post(new Runnable() {
13141            public void run() {
13142                mHandler.removeCallbacks(this);
13143                final boolean succeeded;
13144                synchronized (mInstallLock) {
13145                    succeeded = clearApplicationUserDataLI(packageName, userId);
13146                }
13147                clearExternalStorageDataSync(packageName, userId, true);
13148                if (succeeded) {
13149                    // invoke DeviceStorageMonitor's update method to clear any notifications
13150                    DeviceStorageMonitorInternal
13151                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13152                    if (dsm != null) {
13153                        dsm.checkMemory();
13154                    }
13155                }
13156                if(observer != null) {
13157                    try {
13158                        observer.onRemoveCompleted(packageName, succeeded);
13159                    } catch (RemoteException e) {
13160                        Log.i(TAG, "Observer no longer exists.");
13161                    }
13162                } //end if observer
13163            } //end run
13164        });
13165    }
13166
13167    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13168        if (packageName == null) {
13169            Slog.w(TAG, "Attempt to delete null packageName.");
13170            return false;
13171        }
13172
13173        // Try finding details about the requested package
13174        PackageParser.Package pkg;
13175        synchronized (mPackages) {
13176            pkg = mPackages.get(packageName);
13177            if (pkg == null) {
13178                final PackageSetting ps = mSettings.mPackages.get(packageName);
13179                if (ps != null) {
13180                    pkg = ps.pkg;
13181                }
13182            }
13183
13184            if (pkg == null) {
13185                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13186                return false;
13187            }
13188
13189            PackageSetting ps = (PackageSetting) pkg.mExtras;
13190            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13191        }
13192
13193        // Always delete data directories for package, even if we found no other
13194        // record of app. This helps users recover from UID mismatches without
13195        // resorting to a full data wipe.
13196        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13197        if (retCode < 0) {
13198            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13199            return false;
13200        }
13201
13202        final int appId = pkg.applicationInfo.uid;
13203        removeKeystoreDataIfNeeded(userId, appId);
13204
13205        // Create a native library symlink only if we have native libraries
13206        // and if the native libraries are 32 bit libraries. We do not provide
13207        // this symlink for 64 bit libraries.
13208        if (pkg.applicationInfo.primaryCpuAbi != null &&
13209                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13210            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13211            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13212                    nativeLibPath, userId) < 0) {
13213                Slog.w(TAG, "Failed linking native library dir");
13214                return false;
13215            }
13216        }
13217
13218        return true;
13219    }
13220
13221    /**
13222     * Reverts user permission state changes (permissions and flags).
13223     *
13224     * @param ps The package for which to reset.
13225     * @param userId The device user for which to do a reset.
13226     */
13227    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13228            final PackageSetting ps, final int userId) {
13229        if (ps.pkg == null) {
13230            return;
13231        }
13232
13233        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13234                | FLAG_PERMISSION_USER_FIXED
13235                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13236
13237        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13238                | FLAG_PERMISSION_POLICY_FIXED;
13239
13240        boolean writeInstallPermissions = false;
13241        boolean writeRuntimePermissions = false;
13242
13243        final int permissionCount = ps.pkg.requestedPermissions.size();
13244        for (int i = 0; i < permissionCount; i++) {
13245            String permission = ps.pkg.requestedPermissions.get(i);
13246
13247            BasePermission bp = mSettings.mPermissions.get(permission);
13248            if (bp == null) {
13249                continue;
13250            }
13251
13252            // If shared user we just reset the state to which only this app contributed.
13253            if (ps.sharedUser != null) {
13254                boolean used = false;
13255                final int packageCount = ps.sharedUser.packages.size();
13256                for (int j = 0; j < packageCount; j++) {
13257                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13258                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13259                            && pkg.pkg.requestedPermissions.contains(permission)) {
13260                        used = true;
13261                        break;
13262                    }
13263                }
13264                if (used) {
13265                    continue;
13266                }
13267            }
13268
13269            PermissionsState permissionsState = ps.getPermissionsState();
13270
13271            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13272
13273            // Always clear the user settable flags.
13274            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13275                    bp.name) != null;
13276            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13277                if (hasInstallState) {
13278                    writeInstallPermissions = true;
13279                } else {
13280                    writeRuntimePermissions = true;
13281                }
13282            }
13283
13284            // Below is only runtime permission handling.
13285            if (!bp.isRuntime()) {
13286                continue;
13287            }
13288
13289            // Never clobber system or policy.
13290            if ((oldFlags & policyOrSystemFlags) != 0) {
13291                continue;
13292            }
13293
13294            // If this permission was granted by default, make sure it is.
13295            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13296                if (permissionsState.grantRuntimePermission(bp, userId)
13297                        != PERMISSION_OPERATION_FAILURE) {
13298                    writeRuntimePermissions = true;
13299                }
13300            } else {
13301                // Otherwise, reset the permission.
13302                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13303                switch (revokeResult) {
13304                    case PERMISSION_OPERATION_SUCCESS: {
13305                        writeRuntimePermissions = true;
13306                    } break;
13307
13308                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13309                        writeRuntimePermissions = true;
13310                        // If gids changed for this user, kill all affected packages.
13311                        mHandler.post(new Runnable() {
13312                            @Override
13313                            public void run() {
13314                                // This has to happen with no lock held.
13315                                killSettingPackagesForUser(ps, userId,
13316                                        KILL_APP_REASON_GIDS_CHANGED);
13317                            }
13318                        });
13319                    } break;
13320                }
13321            }
13322        }
13323
13324        // Synchronously write as we are taking permissions away.
13325        if (writeRuntimePermissions) {
13326            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13327        }
13328
13329        // Synchronously write as we are taking permissions away.
13330        if (writeInstallPermissions) {
13331            mSettings.writeLPr();
13332        }
13333    }
13334
13335    /**
13336     * Remove entries from the keystore daemon. Will only remove it if the
13337     * {@code appId} is valid.
13338     */
13339    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13340        if (appId < 0) {
13341            return;
13342        }
13343
13344        final KeyStore keyStore = KeyStore.getInstance();
13345        if (keyStore != null) {
13346            if (userId == UserHandle.USER_ALL) {
13347                for (final int individual : sUserManager.getUserIds()) {
13348                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13349                }
13350            } else {
13351                keyStore.clearUid(UserHandle.getUid(userId, appId));
13352            }
13353        } else {
13354            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13355        }
13356    }
13357
13358    @Override
13359    public void deleteApplicationCacheFiles(final String packageName,
13360            final IPackageDataObserver observer) {
13361        mContext.enforceCallingOrSelfPermission(
13362                android.Manifest.permission.DELETE_CACHE_FILES, null);
13363        // Queue up an async operation since the package deletion may take a little while.
13364        final int userId = UserHandle.getCallingUserId();
13365        mHandler.post(new Runnable() {
13366            public void run() {
13367                mHandler.removeCallbacks(this);
13368                final boolean succeded;
13369                synchronized (mInstallLock) {
13370                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13371                }
13372                clearExternalStorageDataSync(packageName, userId, false);
13373                if (observer != null) {
13374                    try {
13375                        observer.onRemoveCompleted(packageName, succeded);
13376                    } catch (RemoteException e) {
13377                        Log.i(TAG, "Observer no longer exists.");
13378                    }
13379                } //end if observer
13380            } //end run
13381        });
13382    }
13383
13384    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13385        if (packageName == null) {
13386            Slog.w(TAG, "Attempt to delete null packageName.");
13387            return false;
13388        }
13389        PackageParser.Package p;
13390        synchronized (mPackages) {
13391            p = mPackages.get(packageName);
13392        }
13393        if (p == null) {
13394            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13395            return false;
13396        }
13397        final ApplicationInfo applicationInfo = p.applicationInfo;
13398        if (applicationInfo == null) {
13399            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13400            return false;
13401        }
13402        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13403        if (retCode < 0) {
13404            Slog.w(TAG, "Couldn't remove cache files for package: "
13405                       + packageName + " u" + userId);
13406            return false;
13407        }
13408        return true;
13409    }
13410
13411    @Override
13412    public void getPackageSizeInfo(final String packageName, int userHandle,
13413            final IPackageStatsObserver observer) {
13414        mContext.enforceCallingOrSelfPermission(
13415                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13416        if (packageName == null) {
13417            throw new IllegalArgumentException("Attempt to get size of null packageName");
13418        }
13419
13420        PackageStats stats = new PackageStats(packageName, userHandle);
13421
13422        /*
13423         * Queue up an async operation since the package measurement may take a
13424         * little while.
13425         */
13426        Message msg = mHandler.obtainMessage(INIT_COPY);
13427        msg.obj = new MeasureParams(stats, observer);
13428        mHandler.sendMessage(msg);
13429    }
13430
13431    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13432            PackageStats pStats) {
13433        if (packageName == null) {
13434            Slog.w(TAG, "Attempt to get size of null packageName.");
13435            return false;
13436        }
13437        PackageParser.Package p;
13438        boolean dataOnly = false;
13439        String libDirRoot = null;
13440        String asecPath = null;
13441        PackageSetting ps = null;
13442        synchronized (mPackages) {
13443            p = mPackages.get(packageName);
13444            ps = mSettings.mPackages.get(packageName);
13445            if(p == null) {
13446                dataOnly = true;
13447                if((ps == null) || (ps.pkg == null)) {
13448                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13449                    return false;
13450                }
13451                p = ps.pkg;
13452            }
13453            if (ps != null) {
13454                libDirRoot = ps.legacyNativeLibraryPathString;
13455            }
13456            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13457                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13458                if (secureContainerId != null) {
13459                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13460                }
13461            }
13462        }
13463        String publicSrcDir = null;
13464        if(!dataOnly) {
13465            final ApplicationInfo applicationInfo = p.applicationInfo;
13466            if (applicationInfo == null) {
13467                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13468                return false;
13469            }
13470            if (p.isForwardLocked()) {
13471                publicSrcDir = applicationInfo.getBaseResourcePath();
13472            }
13473        }
13474        // TODO: extend to measure size of split APKs
13475        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13476        // not just the first level.
13477        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13478        // just the primary.
13479        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13480        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13481                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13482        if (res < 0) {
13483            return false;
13484        }
13485
13486        // Fix-up for forward-locked applications in ASEC containers.
13487        if (!isExternal(p)) {
13488            pStats.codeSize += pStats.externalCodeSize;
13489            pStats.externalCodeSize = 0L;
13490        }
13491
13492        return true;
13493    }
13494
13495
13496    @Override
13497    public void addPackageToPreferred(String packageName) {
13498        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13499    }
13500
13501    @Override
13502    public void removePackageFromPreferred(String packageName) {
13503        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13504    }
13505
13506    @Override
13507    public List<PackageInfo> getPreferredPackages(int flags) {
13508        return new ArrayList<PackageInfo>();
13509    }
13510
13511    private int getUidTargetSdkVersionLockedLPr(int uid) {
13512        Object obj = mSettings.getUserIdLPr(uid);
13513        if (obj instanceof SharedUserSetting) {
13514            final SharedUserSetting sus = (SharedUserSetting) obj;
13515            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13516            final Iterator<PackageSetting> it = sus.packages.iterator();
13517            while (it.hasNext()) {
13518                final PackageSetting ps = it.next();
13519                if (ps.pkg != null) {
13520                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13521                    if (v < vers) vers = v;
13522                }
13523            }
13524            return vers;
13525        } else if (obj instanceof PackageSetting) {
13526            final PackageSetting ps = (PackageSetting) obj;
13527            if (ps.pkg != null) {
13528                return ps.pkg.applicationInfo.targetSdkVersion;
13529            }
13530        }
13531        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13532    }
13533
13534    @Override
13535    public void addPreferredActivity(IntentFilter filter, int match,
13536            ComponentName[] set, ComponentName activity, int userId) {
13537        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13538                "Adding preferred");
13539    }
13540
13541    private void addPreferredActivityInternal(IntentFilter filter, int match,
13542            ComponentName[] set, ComponentName activity, boolean always, int userId,
13543            String opname) {
13544        // writer
13545        int callingUid = Binder.getCallingUid();
13546        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13547        if (filter.countActions() == 0) {
13548            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13549            return;
13550        }
13551        synchronized (mPackages) {
13552            if (mContext.checkCallingOrSelfPermission(
13553                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13554                    != PackageManager.PERMISSION_GRANTED) {
13555                if (getUidTargetSdkVersionLockedLPr(callingUid)
13556                        < Build.VERSION_CODES.FROYO) {
13557                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13558                            + callingUid);
13559                    return;
13560                }
13561                mContext.enforceCallingOrSelfPermission(
13562                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13563            }
13564
13565            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13566            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13567                    + userId + ":");
13568            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13569            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13570            scheduleWritePackageRestrictionsLocked(userId);
13571        }
13572    }
13573
13574    @Override
13575    public void replacePreferredActivity(IntentFilter filter, int match,
13576            ComponentName[] set, ComponentName activity, int userId) {
13577        if (filter.countActions() != 1) {
13578            throw new IllegalArgumentException(
13579                    "replacePreferredActivity expects filter to have only 1 action.");
13580        }
13581        if (filter.countDataAuthorities() != 0
13582                || filter.countDataPaths() != 0
13583                || filter.countDataSchemes() > 1
13584                || filter.countDataTypes() != 0) {
13585            throw new IllegalArgumentException(
13586                    "replacePreferredActivity expects filter to have no data authorities, " +
13587                    "paths, or types; and at most one scheme.");
13588        }
13589
13590        final int callingUid = Binder.getCallingUid();
13591        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13592        synchronized (mPackages) {
13593            if (mContext.checkCallingOrSelfPermission(
13594                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13595                    != PackageManager.PERMISSION_GRANTED) {
13596                if (getUidTargetSdkVersionLockedLPr(callingUid)
13597                        < Build.VERSION_CODES.FROYO) {
13598                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13599                            + Binder.getCallingUid());
13600                    return;
13601                }
13602                mContext.enforceCallingOrSelfPermission(
13603                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13604            }
13605
13606            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13607            if (pir != null) {
13608                // Get all of the existing entries that exactly match this filter.
13609                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13610                if (existing != null && existing.size() == 1) {
13611                    PreferredActivity cur = existing.get(0);
13612                    if (DEBUG_PREFERRED) {
13613                        Slog.i(TAG, "Checking replace of preferred:");
13614                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13615                        if (!cur.mPref.mAlways) {
13616                            Slog.i(TAG, "  -- CUR; not mAlways!");
13617                        } else {
13618                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13619                            Slog.i(TAG, "  -- CUR: mSet="
13620                                    + Arrays.toString(cur.mPref.mSetComponents));
13621                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13622                            Slog.i(TAG, "  -- NEW: mMatch="
13623                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13624                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13625                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13626                        }
13627                    }
13628                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13629                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13630                            && cur.mPref.sameSet(set)) {
13631                        // Setting the preferred activity to what it happens to be already
13632                        if (DEBUG_PREFERRED) {
13633                            Slog.i(TAG, "Replacing with same preferred activity "
13634                                    + cur.mPref.mShortComponent + " for user "
13635                                    + userId + ":");
13636                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13637                        }
13638                        return;
13639                    }
13640                }
13641
13642                if (existing != null) {
13643                    if (DEBUG_PREFERRED) {
13644                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13645                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13646                    }
13647                    for (int i = 0; i < existing.size(); i++) {
13648                        PreferredActivity pa = existing.get(i);
13649                        if (DEBUG_PREFERRED) {
13650                            Slog.i(TAG, "Removing existing preferred activity "
13651                                    + pa.mPref.mComponent + ":");
13652                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13653                        }
13654                        pir.removeFilter(pa);
13655                    }
13656                }
13657            }
13658            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13659                    "Replacing preferred");
13660        }
13661    }
13662
13663    @Override
13664    public void clearPackagePreferredActivities(String packageName) {
13665        final int uid = Binder.getCallingUid();
13666        // writer
13667        synchronized (mPackages) {
13668            PackageParser.Package pkg = mPackages.get(packageName);
13669            if (pkg == null || pkg.applicationInfo.uid != uid) {
13670                if (mContext.checkCallingOrSelfPermission(
13671                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13672                        != PackageManager.PERMISSION_GRANTED) {
13673                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13674                            < Build.VERSION_CODES.FROYO) {
13675                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13676                                + Binder.getCallingUid());
13677                        return;
13678                    }
13679                    mContext.enforceCallingOrSelfPermission(
13680                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13681                }
13682            }
13683
13684            int user = UserHandle.getCallingUserId();
13685            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13686                scheduleWritePackageRestrictionsLocked(user);
13687            }
13688        }
13689    }
13690
13691    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13692    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13693        ArrayList<PreferredActivity> removed = null;
13694        boolean changed = false;
13695        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13696            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13697            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13698            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13699                continue;
13700            }
13701            Iterator<PreferredActivity> it = pir.filterIterator();
13702            while (it.hasNext()) {
13703                PreferredActivity pa = it.next();
13704                // Mark entry for removal only if it matches the package name
13705                // and the entry is of type "always".
13706                if (packageName == null ||
13707                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13708                                && pa.mPref.mAlways)) {
13709                    if (removed == null) {
13710                        removed = new ArrayList<PreferredActivity>();
13711                    }
13712                    removed.add(pa);
13713                }
13714            }
13715            if (removed != null) {
13716                for (int j=0; j<removed.size(); j++) {
13717                    PreferredActivity pa = removed.get(j);
13718                    pir.removeFilter(pa);
13719                }
13720                changed = true;
13721            }
13722        }
13723        return changed;
13724    }
13725
13726    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13727    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13728        if (userId == UserHandle.USER_ALL) {
13729            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13730                    sUserManager.getUserIds())) {
13731                for (int oneUserId : sUserManager.getUserIds()) {
13732                    scheduleWritePackageRestrictionsLocked(oneUserId);
13733                }
13734            }
13735        } else {
13736            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13737                scheduleWritePackageRestrictionsLocked(userId);
13738            }
13739        }
13740    }
13741
13742
13743    void clearDefaultBrowserIfNeeded(String packageName) {
13744        for (int oneUserId : sUserManager.getUserIds()) {
13745            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13746            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13747            if (packageName.equals(defaultBrowserPackageName)) {
13748                setDefaultBrowserPackageName(null, oneUserId);
13749            }
13750        }
13751    }
13752
13753    @Override
13754    public void resetPreferredActivities(int userId) {
13755        mContext.enforceCallingOrSelfPermission(
13756                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13757        // writer
13758        synchronized (mPackages) {
13759            clearPackagePreferredActivitiesLPw(null, userId);
13760            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13761            applyFactoryDefaultBrowserLPw(userId);
13762            primeDomainVerificationsLPw(userId);
13763
13764            scheduleWritePackageRestrictionsLocked(userId);
13765        }
13766    }
13767
13768    @Override
13769    public int getPreferredActivities(List<IntentFilter> outFilters,
13770            List<ComponentName> outActivities, String packageName) {
13771
13772        int num = 0;
13773        final int userId = UserHandle.getCallingUserId();
13774        // reader
13775        synchronized (mPackages) {
13776            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13777            if (pir != null) {
13778                final Iterator<PreferredActivity> it = pir.filterIterator();
13779                while (it.hasNext()) {
13780                    final PreferredActivity pa = it.next();
13781                    if (packageName == null
13782                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13783                                    && pa.mPref.mAlways)) {
13784                        if (outFilters != null) {
13785                            outFilters.add(new IntentFilter(pa));
13786                        }
13787                        if (outActivities != null) {
13788                            outActivities.add(pa.mPref.mComponent);
13789                        }
13790                    }
13791                }
13792            }
13793        }
13794
13795        return num;
13796    }
13797
13798    @Override
13799    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13800            int userId) {
13801        int callingUid = Binder.getCallingUid();
13802        if (callingUid != Process.SYSTEM_UID) {
13803            throw new SecurityException(
13804                    "addPersistentPreferredActivity can only be run by the system");
13805        }
13806        if (filter.countActions() == 0) {
13807            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13808            return;
13809        }
13810        synchronized (mPackages) {
13811            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13812                    " :");
13813            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13814            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13815                    new PersistentPreferredActivity(filter, activity));
13816            scheduleWritePackageRestrictionsLocked(userId);
13817        }
13818    }
13819
13820    @Override
13821    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13822        int callingUid = Binder.getCallingUid();
13823        if (callingUid != Process.SYSTEM_UID) {
13824            throw new SecurityException(
13825                    "clearPackagePersistentPreferredActivities can only be run by the system");
13826        }
13827        ArrayList<PersistentPreferredActivity> removed = null;
13828        boolean changed = false;
13829        synchronized (mPackages) {
13830            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13831                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13832                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13833                        .valueAt(i);
13834                if (userId != thisUserId) {
13835                    continue;
13836                }
13837                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13838                while (it.hasNext()) {
13839                    PersistentPreferredActivity ppa = it.next();
13840                    // Mark entry for removal only if it matches the package name.
13841                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13842                        if (removed == null) {
13843                            removed = new ArrayList<PersistentPreferredActivity>();
13844                        }
13845                        removed.add(ppa);
13846                    }
13847                }
13848                if (removed != null) {
13849                    for (int j=0; j<removed.size(); j++) {
13850                        PersistentPreferredActivity ppa = removed.get(j);
13851                        ppir.removeFilter(ppa);
13852                    }
13853                    changed = true;
13854                }
13855            }
13856
13857            if (changed) {
13858                scheduleWritePackageRestrictionsLocked(userId);
13859            }
13860        }
13861    }
13862
13863    /**
13864     * Common machinery for picking apart a restored XML blob and passing
13865     * it to a caller-supplied functor to be applied to the running system.
13866     */
13867    private void restoreFromXml(XmlPullParser parser, int userId,
13868            String expectedStartTag, BlobXmlRestorer functor)
13869            throws IOException, XmlPullParserException {
13870        int type;
13871        while ((type = parser.next()) != XmlPullParser.START_TAG
13872                && type != XmlPullParser.END_DOCUMENT) {
13873        }
13874        if (type != XmlPullParser.START_TAG) {
13875            // oops didn't find a start tag?!
13876            if (DEBUG_BACKUP) {
13877                Slog.e(TAG, "Didn't find start tag during restore");
13878            }
13879            return;
13880        }
13881
13882        // this is supposed to be TAG_PREFERRED_BACKUP
13883        if (!expectedStartTag.equals(parser.getName())) {
13884            if (DEBUG_BACKUP) {
13885                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13886            }
13887            return;
13888        }
13889
13890        // skip interfering stuff, then we're aligned with the backing implementation
13891        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13892        functor.apply(parser, userId);
13893    }
13894
13895    private interface BlobXmlRestorer {
13896        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13897    }
13898
13899    /**
13900     * Non-Binder method, support for the backup/restore mechanism: write the
13901     * full set of preferred activities in its canonical XML format.  Returns the
13902     * XML output as a byte array, or null if there is none.
13903     */
13904    @Override
13905    public byte[] getPreferredActivityBackup(int userId) {
13906        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13907            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13908        }
13909
13910        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13911        try {
13912            final XmlSerializer serializer = new FastXmlSerializer();
13913            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13914            serializer.startDocument(null, true);
13915            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13916
13917            synchronized (mPackages) {
13918                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13919            }
13920
13921            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13922            serializer.endDocument();
13923            serializer.flush();
13924        } catch (Exception e) {
13925            if (DEBUG_BACKUP) {
13926                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13927            }
13928            return null;
13929        }
13930
13931        return dataStream.toByteArray();
13932    }
13933
13934    @Override
13935    public void restorePreferredActivities(byte[] backup, int userId) {
13936        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13937            throw new SecurityException("Only the system may call restorePreferredActivities()");
13938        }
13939
13940        try {
13941            final XmlPullParser parser = Xml.newPullParser();
13942            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13943            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13944                    new BlobXmlRestorer() {
13945                        @Override
13946                        public void apply(XmlPullParser parser, int userId)
13947                                throws XmlPullParserException, IOException {
13948                            synchronized (mPackages) {
13949                                mSettings.readPreferredActivitiesLPw(parser, userId);
13950                            }
13951                        }
13952                    } );
13953        } catch (Exception e) {
13954            if (DEBUG_BACKUP) {
13955                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13956            }
13957        }
13958    }
13959
13960    /**
13961     * Non-Binder method, support for the backup/restore mechanism: write the
13962     * default browser (etc) settings in its canonical XML format.  Returns the default
13963     * browser XML representation as a byte array, or null if there is none.
13964     */
13965    @Override
13966    public byte[] getDefaultAppsBackup(int userId) {
13967        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13968            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13969        }
13970
13971        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13972        try {
13973            final XmlSerializer serializer = new FastXmlSerializer();
13974            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13975            serializer.startDocument(null, true);
13976            serializer.startTag(null, TAG_DEFAULT_APPS);
13977
13978            synchronized (mPackages) {
13979                mSettings.writeDefaultAppsLPr(serializer, userId);
13980            }
13981
13982            serializer.endTag(null, TAG_DEFAULT_APPS);
13983            serializer.endDocument();
13984            serializer.flush();
13985        } catch (Exception e) {
13986            if (DEBUG_BACKUP) {
13987                Slog.e(TAG, "Unable to write default apps for backup", e);
13988            }
13989            return null;
13990        }
13991
13992        return dataStream.toByteArray();
13993    }
13994
13995    @Override
13996    public void restoreDefaultApps(byte[] backup, int userId) {
13997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13998            throw new SecurityException("Only the system may call restoreDefaultApps()");
13999        }
14000
14001        try {
14002            final XmlPullParser parser = Xml.newPullParser();
14003            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14004            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14005                    new BlobXmlRestorer() {
14006                        @Override
14007                        public void apply(XmlPullParser parser, int userId)
14008                                throws XmlPullParserException, IOException {
14009                            synchronized (mPackages) {
14010                                mSettings.readDefaultAppsLPw(parser, userId);
14011                            }
14012                        }
14013                    } );
14014        } catch (Exception e) {
14015            if (DEBUG_BACKUP) {
14016                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14017            }
14018        }
14019    }
14020
14021    @Override
14022    public byte[] getIntentFilterVerificationBackup(int userId) {
14023        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14024            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14025        }
14026
14027        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14028        try {
14029            final XmlSerializer serializer = new FastXmlSerializer();
14030            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14031            serializer.startDocument(null, true);
14032            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14033
14034            synchronized (mPackages) {
14035                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14036            }
14037
14038            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14039            serializer.endDocument();
14040            serializer.flush();
14041        } catch (Exception e) {
14042            if (DEBUG_BACKUP) {
14043                Slog.e(TAG, "Unable to write default apps for backup", e);
14044            }
14045            return null;
14046        }
14047
14048        return dataStream.toByteArray();
14049    }
14050
14051    @Override
14052    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14053        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14054            throw new SecurityException("Only the system may call restorePreferredActivities()");
14055        }
14056
14057        try {
14058            final XmlPullParser parser = Xml.newPullParser();
14059            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14060            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14061                    new BlobXmlRestorer() {
14062                        @Override
14063                        public void apply(XmlPullParser parser, int userId)
14064                                throws XmlPullParserException, IOException {
14065                            synchronized (mPackages) {
14066                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14067                                mSettings.writeLPr();
14068                            }
14069                        }
14070                    } );
14071        } catch (Exception e) {
14072            if (DEBUG_BACKUP) {
14073                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14074            }
14075        }
14076    }
14077
14078    @Override
14079    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14080            int sourceUserId, int targetUserId, int flags) {
14081        mContext.enforceCallingOrSelfPermission(
14082                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14083        int callingUid = Binder.getCallingUid();
14084        enforceOwnerRights(ownerPackage, callingUid);
14085        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14086        if (intentFilter.countActions() == 0) {
14087            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14088            return;
14089        }
14090        synchronized (mPackages) {
14091            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14092                    ownerPackage, targetUserId, flags);
14093            CrossProfileIntentResolver resolver =
14094                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14095            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14096            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14097            if (existing != null) {
14098                int size = existing.size();
14099                for (int i = 0; i < size; i++) {
14100                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14101                        return;
14102                    }
14103                }
14104            }
14105            resolver.addFilter(newFilter);
14106            scheduleWritePackageRestrictionsLocked(sourceUserId);
14107        }
14108    }
14109
14110    @Override
14111    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14112        mContext.enforceCallingOrSelfPermission(
14113                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14114        int callingUid = Binder.getCallingUid();
14115        enforceOwnerRights(ownerPackage, callingUid);
14116        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14117        synchronized (mPackages) {
14118            CrossProfileIntentResolver resolver =
14119                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14120            ArraySet<CrossProfileIntentFilter> set =
14121                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14122            for (CrossProfileIntentFilter filter : set) {
14123                if (filter.getOwnerPackage().equals(ownerPackage)) {
14124                    resolver.removeFilter(filter);
14125                }
14126            }
14127            scheduleWritePackageRestrictionsLocked(sourceUserId);
14128        }
14129    }
14130
14131    // Enforcing that callingUid is owning pkg on userId
14132    private void enforceOwnerRights(String pkg, int callingUid) {
14133        // The system owns everything.
14134        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14135            return;
14136        }
14137        int callingUserId = UserHandle.getUserId(callingUid);
14138        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14139        if (pi == null) {
14140            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14141                    + callingUserId);
14142        }
14143        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14144            throw new SecurityException("Calling uid " + callingUid
14145                    + " does not own package " + pkg);
14146        }
14147    }
14148
14149    @Override
14150    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14151        Intent intent = new Intent(Intent.ACTION_MAIN);
14152        intent.addCategory(Intent.CATEGORY_HOME);
14153
14154        final int callingUserId = UserHandle.getCallingUserId();
14155        List<ResolveInfo> list = queryIntentActivities(intent, null,
14156                PackageManager.GET_META_DATA, callingUserId);
14157        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14158                true, false, false, callingUserId);
14159
14160        allHomeCandidates.clear();
14161        if (list != null) {
14162            for (ResolveInfo ri : list) {
14163                allHomeCandidates.add(ri);
14164            }
14165        }
14166        return (preferred == null || preferred.activityInfo == null)
14167                ? null
14168                : new ComponentName(preferred.activityInfo.packageName,
14169                        preferred.activityInfo.name);
14170    }
14171
14172    @Override
14173    public void setApplicationEnabledSetting(String appPackageName,
14174            int newState, int flags, int userId, String callingPackage) {
14175        if (!sUserManager.exists(userId)) return;
14176        if (callingPackage == null) {
14177            callingPackage = Integer.toString(Binder.getCallingUid());
14178        }
14179        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14180    }
14181
14182    @Override
14183    public void setComponentEnabledSetting(ComponentName componentName,
14184            int newState, int flags, int userId) {
14185        if (!sUserManager.exists(userId)) return;
14186        setEnabledSetting(componentName.getPackageName(),
14187                componentName.getClassName(), newState, flags, userId, null);
14188    }
14189
14190    private void setEnabledSetting(final String packageName, String className, int newState,
14191            final int flags, int userId, String callingPackage) {
14192        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14193              || newState == COMPONENT_ENABLED_STATE_ENABLED
14194              || newState == COMPONENT_ENABLED_STATE_DISABLED
14195              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14196              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14197            throw new IllegalArgumentException("Invalid new component state: "
14198                    + newState);
14199        }
14200        PackageSetting pkgSetting;
14201        final int uid = Binder.getCallingUid();
14202        final int permission = mContext.checkCallingOrSelfPermission(
14203                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14204        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14205        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14206        boolean sendNow = false;
14207        boolean isApp = (className == null);
14208        String componentName = isApp ? packageName : className;
14209        int packageUid = -1;
14210        ArrayList<String> components;
14211
14212        // writer
14213        synchronized (mPackages) {
14214            pkgSetting = mSettings.mPackages.get(packageName);
14215            if (pkgSetting == null) {
14216                if (className == null) {
14217                    throw new IllegalArgumentException(
14218                            "Unknown package: " + packageName);
14219                }
14220                throw new IllegalArgumentException(
14221                        "Unknown component: " + packageName
14222                        + "/" + className);
14223            }
14224            // Allow root and verify that userId is not being specified by a different user
14225            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14226                throw new SecurityException(
14227                        "Permission Denial: attempt to change component state from pid="
14228                        + Binder.getCallingPid()
14229                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14230            }
14231            if (className == null) {
14232                // We're dealing with an application/package level state change
14233                if (pkgSetting.getEnabled(userId) == newState) {
14234                    // Nothing to do
14235                    return;
14236                }
14237                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14238                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14239                    // Don't care about who enables an app.
14240                    callingPackage = null;
14241                }
14242                pkgSetting.setEnabled(newState, userId, callingPackage);
14243                // pkgSetting.pkg.mSetEnabled = newState;
14244            } else {
14245                // We're dealing with a component level state change
14246                // First, verify that this is a valid class name.
14247                PackageParser.Package pkg = pkgSetting.pkg;
14248                if (pkg == null || !pkg.hasComponentClassName(className)) {
14249                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14250                        throw new IllegalArgumentException("Component class " + className
14251                                + " does not exist in " + packageName);
14252                    } else {
14253                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14254                                + className + " does not exist in " + packageName);
14255                    }
14256                }
14257                switch (newState) {
14258                case COMPONENT_ENABLED_STATE_ENABLED:
14259                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14260                        return;
14261                    }
14262                    break;
14263                case COMPONENT_ENABLED_STATE_DISABLED:
14264                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14265                        return;
14266                    }
14267                    break;
14268                case COMPONENT_ENABLED_STATE_DEFAULT:
14269                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14270                        return;
14271                    }
14272                    break;
14273                default:
14274                    Slog.e(TAG, "Invalid new component state: " + newState);
14275                    return;
14276                }
14277            }
14278            scheduleWritePackageRestrictionsLocked(userId);
14279            components = mPendingBroadcasts.get(userId, packageName);
14280            final boolean newPackage = components == null;
14281            if (newPackage) {
14282                components = new ArrayList<String>();
14283            }
14284            if (!components.contains(componentName)) {
14285                components.add(componentName);
14286            }
14287            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14288                sendNow = true;
14289                // Purge entry from pending broadcast list if another one exists already
14290                // since we are sending one right away.
14291                mPendingBroadcasts.remove(userId, packageName);
14292            } else {
14293                if (newPackage) {
14294                    mPendingBroadcasts.put(userId, packageName, components);
14295                }
14296                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14297                    // Schedule a message
14298                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14299                }
14300            }
14301        }
14302
14303        long callingId = Binder.clearCallingIdentity();
14304        try {
14305            if (sendNow) {
14306                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14307                sendPackageChangedBroadcast(packageName,
14308                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14309            }
14310        } finally {
14311            Binder.restoreCallingIdentity(callingId);
14312        }
14313    }
14314
14315    private void sendPackageChangedBroadcast(String packageName,
14316            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14317        if (DEBUG_INSTALL)
14318            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14319                    + componentNames);
14320        Bundle extras = new Bundle(4);
14321        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14322        String nameList[] = new String[componentNames.size()];
14323        componentNames.toArray(nameList);
14324        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14325        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14326        extras.putInt(Intent.EXTRA_UID, packageUid);
14327        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14328                new int[] {UserHandle.getUserId(packageUid)});
14329    }
14330
14331    @Override
14332    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14333        if (!sUserManager.exists(userId)) return;
14334        final int uid = Binder.getCallingUid();
14335        final int permission = mContext.checkCallingOrSelfPermission(
14336                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14337        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14338        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14339        // writer
14340        synchronized (mPackages) {
14341            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14342                    allowedByPermission, uid, userId)) {
14343                scheduleWritePackageRestrictionsLocked(userId);
14344            }
14345        }
14346    }
14347
14348    @Override
14349    public String getInstallerPackageName(String packageName) {
14350        // reader
14351        synchronized (mPackages) {
14352            return mSettings.getInstallerPackageNameLPr(packageName);
14353        }
14354    }
14355
14356    @Override
14357    public int getApplicationEnabledSetting(String packageName, int userId) {
14358        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14359        int uid = Binder.getCallingUid();
14360        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14361        // reader
14362        synchronized (mPackages) {
14363            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14364        }
14365    }
14366
14367    @Override
14368    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14369        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14370        int uid = Binder.getCallingUid();
14371        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14372        // reader
14373        synchronized (mPackages) {
14374            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14375        }
14376    }
14377
14378    @Override
14379    public void enterSafeMode() {
14380        enforceSystemOrRoot("Only the system can request entering safe mode");
14381
14382        if (!mSystemReady) {
14383            mSafeMode = true;
14384        }
14385    }
14386
14387    @Override
14388    public void systemReady() {
14389        mSystemReady = true;
14390
14391        // Read the compatibilty setting when the system is ready.
14392        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14393                mContext.getContentResolver(),
14394                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14395        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14396        if (DEBUG_SETTINGS) {
14397            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14398        }
14399
14400        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14401
14402        synchronized (mPackages) {
14403            // Verify that all of the preferred activity components actually
14404            // exist.  It is possible for applications to be updated and at
14405            // that point remove a previously declared activity component that
14406            // had been set as a preferred activity.  We try to clean this up
14407            // the next time we encounter that preferred activity, but it is
14408            // possible for the user flow to never be able to return to that
14409            // situation so here we do a sanity check to make sure we haven't
14410            // left any junk around.
14411            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14412            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14413                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14414                removed.clear();
14415                for (PreferredActivity pa : pir.filterSet()) {
14416                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14417                        removed.add(pa);
14418                    }
14419                }
14420                if (removed.size() > 0) {
14421                    for (int r=0; r<removed.size(); r++) {
14422                        PreferredActivity pa = removed.get(r);
14423                        Slog.w(TAG, "Removing dangling preferred activity: "
14424                                + pa.mPref.mComponent);
14425                        pir.removeFilter(pa);
14426                    }
14427                    mSettings.writePackageRestrictionsLPr(
14428                            mSettings.mPreferredActivities.keyAt(i));
14429                }
14430            }
14431
14432            for (int userId : UserManagerService.getInstance().getUserIds()) {
14433                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14434                    grantPermissionsUserIds = ArrayUtils.appendInt(
14435                            grantPermissionsUserIds, userId);
14436                }
14437            }
14438        }
14439        sUserManager.systemReady();
14440
14441        // If we upgraded grant all default permissions before kicking off.
14442        for (int userId : grantPermissionsUserIds) {
14443            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14444        }
14445
14446        // Kick off any messages waiting for system ready
14447        if (mPostSystemReadyMessages != null) {
14448            for (Message msg : mPostSystemReadyMessages) {
14449                msg.sendToTarget();
14450            }
14451            mPostSystemReadyMessages = null;
14452        }
14453
14454        // Watch for external volumes that come and go over time
14455        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14456        storage.registerListener(mStorageListener);
14457
14458        mInstallerService.systemReady();
14459        mPackageDexOptimizer.systemReady();
14460
14461        MountServiceInternal mountServiceInternal = LocalServices.getService(
14462                MountServiceInternal.class);
14463        mountServiceInternal.addExternalStoragePolicy(
14464                new MountServiceInternal.ExternalStorageMountPolicy() {
14465            @Override
14466            public int getMountMode(int uid, String packageName) {
14467                if (Process.isIsolated(uid)) {
14468                    return Zygote.MOUNT_EXTERNAL_NONE;
14469                }
14470                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14471                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14472                }
14473                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14474                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14475                }
14476                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14477                    return Zygote.MOUNT_EXTERNAL_READ;
14478                }
14479                return Zygote.MOUNT_EXTERNAL_WRITE;
14480            }
14481
14482            @Override
14483            public boolean hasExternalStorage(int uid, String packageName) {
14484                return true;
14485            }
14486        });
14487    }
14488
14489    @Override
14490    public boolean isSafeMode() {
14491        return mSafeMode;
14492    }
14493
14494    @Override
14495    public boolean hasSystemUidErrors() {
14496        return mHasSystemUidErrors;
14497    }
14498
14499    static String arrayToString(int[] array) {
14500        StringBuffer buf = new StringBuffer(128);
14501        buf.append('[');
14502        if (array != null) {
14503            for (int i=0; i<array.length; i++) {
14504                if (i > 0) buf.append(", ");
14505                buf.append(array[i]);
14506            }
14507        }
14508        buf.append(']');
14509        return buf.toString();
14510    }
14511
14512    static class DumpState {
14513        public static final int DUMP_LIBS = 1 << 0;
14514        public static final int DUMP_FEATURES = 1 << 1;
14515        public static final int DUMP_RESOLVERS = 1 << 2;
14516        public static final int DUMP_PERMISSIONS = 1 << 3;
14517        public static final int DUMP_PACKAGES = 1 << 4;
14518        public static final int DUMP_SHARED_USERS = 1 << 5;
14519        public static final int DUMP_MESSAGES = 1 << 6;
14520        public static final int DUMP_PROVIDERS = 1 << 7;
14521        public static final int DUMP_VERIFIERS = 1 << 8;
14522        public static final int DUMP_PREFERRED = 1 << 9;
14523        public static final int DUMP_PREFERRED_XML = 1 << 10;
14524        public static final int DUMP_KEYSETS = 1 << 11;
14525        public static final int DUMP_VERSION = 1 << 12;
14526        public static final int DUMP_INSTALLS = 1 << 13;
14527        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14528        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14529
14530        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14531
14532        private int mTypes;
14533
14534        private int mOptions;
14535
14536        private boolean mTitlePrinted;
14537
14538        private SharedUserSetting mSharedUser;
14539
14540        public boolean isDumping(int type) {
14541            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14542                return true;
14543            }
14544
14545            return (mTypes & type) != 0;
14546        }
14547
14548        public void setDump(int type) {
14549            mTypes |= type;
14550        }
14551
14552        public boolean isOptionEnabled(int option) {
14553            return (mOptions & option) != 0;
14554        }
14555
14556        public void setOptionEnabled(int option) {
14557            mOptions |= option;
14558        }
14559
14560        public boolean onTitlePrinted() {
14561            final boolean printed = mTitlePrinted;
14562            mTitlePrinted = true;
14563            return printed;
14564        }
14565
14566        public boolean getTitlePrinted() {
14567            return mTitlePrinted;
14568        }
14569
14570        public void setTitlePrinted(boolean enabled) {
14571            mTitlePrinted = enabled;
14572        }
14573
14574        public SharedUserSetting getSharedUser() {
14575            return mSharedUser;
14576        }
14577
14578        public void setSharedUser(SharedUserSetting user) {
14579            mSharedUser = user;
14580        }
14581    }
14582
14583    @Override
14584    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14585        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14586                != PackageManager.PERMISSION_GRANTED) {
14587            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14588                    + Binder.getCallingPid()
14589                    + ", uid=" + Binder.getCallingUid()
14590                    + " without permission "
14591                    + android.Manifest.permission.DUMP);
14592            return;
14593        }
14594
14595        DumpState dumpState = new DumpState();
14596        boolean fullPreferred = false;
14597        boolean checkin = false;
14598
14599        String packageName = null;
14600        ArraySet<String> permissionNames = null;
14601
14602        int opti = 0;
14603        while (opti < args.length) {
14604            String opt = args[opti];
14605            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14606                break;
14607            }
14608            opti++;
14609
14610            if ("-a".equals(opt)) {
14611                // Right now we only know how to print all.
14612            } else if ("-h".equals(opt)) {
14613                pw.println("Package manager dump options:");
14614                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14615                pw.println("    --checkin: dump for a checkin");
14616                pw.println("    -f: print details of intent filters");
14617                pw.println("    -h: print this help");
14618                pw.println("  cmd may be one of:");
14619                pw.println("    l[ibraries]: list known shared libraries");
14620                pw.println("    f[ibraries]: list device features");
14621                pw.println("    k[eysets]: print known keysets");
14622                pw.println("    r[esolvers]: dump intent resolvers");
14623                pw.println("    perm[issions]: dump permissions");
14624                pw.println("    permission [name ...]: dump declaration and use of given permission");
14625                pw.println("    pref[erred]: print preferred package settings");
14626                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14627                pw.println("    prov[iders]: dump content providers");
14628                pw.println("    p[ackages]: dump installed packages");
14629                pw.println("    s[hared-users]: dump shared user IDs");
14630                pw.println("    m[essages]: print collected runtime messages");
14631                pw.println("    v[erifiers]: print package verifier info");
14632                pw.println("    version: print database version info");
14633                pw.println("    write: write current settings now");
14634                pw.println("    <package.name>: info about given package");
14635                pw.println("    installs: details about install sessions");
14636                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14637                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14638                return;
14639            } else if ("--checkin".equals(opt)) {
14640                checkin = true;
14641            } else if ("-f".equals(opt)) {
14642                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14643            } else {
14644                pw.println("Unknown argument: " + opt + "; use -h for help");
14645            }
14646        }
14647
14648        // Is the caller requesting to dump a particular piece of data?
14649        if (opti < args.length) {
14650            String cmd = args[opti];
14651            opti++;
14652            // Is this a package name?
14653            if ("android".equals(cmd) || cmd.contains(".")) {
14654                packageName = cmd;
14655                // When dumping a single package, we always dump all of its
14656                // filter information since the amount of data will be reasonable.
14657                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14658            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14659                dumpState.setDump(DumpState.DUMP_LIBS);
14660            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14661                dumpState.setDump(DumpState.DUMP_FEATURES);
14662            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14663                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14664            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14665                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14666            } else if ("permission".equals(cmd)) {
14667                if (opti >= args.length) {
14668                    pw.println("Error: permission requires permission name");
14669                    return;
14670                }
14671                permissionNames = new ArraySet<>();
14672                while (opti < args.length) {
14673                    permissionNames.add(args[opti]);
14674                    opti++;
14675                }
14676                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14677                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14678            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14679                dumpState.setDump(DumpState.DUMP_PREFERRED);
14680            } else if ("preferred-xml".equals(cmd)) {
14681                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14682                if (opti < args.length && "--full".equals(args[opti])) {
14683                    fullPreferred = true;
14684                    opti++;
14685                }
14686            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14687                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14688            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14689                dumpState.setDump(DumpState.DUMP_PACKAGES);
14690            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14691                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14692            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14693                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14694            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14695                dumpState.setDump(DumpState.DUMP_MESSAGES);
14696            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14697                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14698            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14699                    || "intent-filter-verifiers".equals(cmd)) {
14700                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14701            } else if ("version".equals(cmd)) {
14702                dumpState.setDump(DumpState.DUMP_VERSION);
14703            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14704                dumpState.setDump(DumpState.DUMP_KEYSETS);
14705            } else if ("installs".equals(cmd)) {
14706                dumpState.setDump(DumpState.DUMP_INSTALLS);
14707            } else if ("write".equals(cmd)) {
14708                synchronized (mPackages) {
14709                    mSettings.writeLPr();
14710                    pw.println("Settings written.");
14711                    return;
14712                }
14713            }
14714        }
14715
14716        if (checkin) {
14717            pw.println("vers,1");
14718        }
14719
14720        // reader
14721        synchronized (mPackages) {
14722            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14723                if (!checkin) {
14724                    if (dumpState.onTitlePrinted())
14725                        pw.println();
14726                    pw.println("Database versions:");
14727                    pw.print("  SDK Version:");
14728                    pw.print(" internal=");
14729                    pw.print(mSettings.mInternalSdkPlatform);
14730                    pw.print(" external=");
14731                    pw.println(mSettings.mExternalSdkPlatform);
14732                    pw.print("  DB Version:");
14733                    pw.print(" internal=");
14734                    pw.print(mSettings.mInternalDatabaseVersion);
14735                    pw.print(" external=");
14736                    pw.println(mSettings.mExternalDatabaseVersion);
14737                }
14738            }
14739
14740            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14741                if (!checkin) {
14742                    if (dumpState.onTitlePrinted())
14743                        pw.println();
14744                    pw.println("Verifiers:");
14745                    pw.print("  Required: ");
14746                    pw.print(mRequiredVerifierPackage);
14747                    pw.print(" (uid=");
14748                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14749                    pw.println(")");
14750                } else if (mRequiredVerifierPackage != null) {
14751                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14752                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14753                }
14754            }
14755
14756            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14757                    packageName == null) {
14758                if (mIntentFilterVerifierComponent != null) {
14759                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14760                    if (!checkin) {
14761                        if (dumpState.onTitlePrinted())
14762                            pw.println();
14763                        pw.println("Intent Filter Verifier:");
14764                        pw.print("  Using: ");
14765                        pw.print(verifierPackageName);
14766                        pw.print(" (uid=");
14767                        pw.print(getPackageUid(verifierPackageName, 0));
14768                        pw.println(")");
14769                    } else if (verifierPackageName != null) {
14770                        pw.print("ifv,"); pw.print(verifierPackageName);
14771                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14772                    }
14773                } else {
14774                    pw.println();
14775                    pw.println("No Intent Filter Verifier available!");
14776                }
14777            }
14778
14779            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14780                boolean printedHeader = false;
14781                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14782                while (it.hasNext()) {
14783                    String name = it.next();
14784                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14785                    if (!checkin) {
14786                        if (!printedHeader) {
14787                            if (dumpState.onTitlePrinted())
14788                                pw.println();
14789                            pw.println("Libraries:");
14790                            printedHeader = true;
14791                        }
14792                        pw.print("  ");
14793                    } else {
14794                        pw.print("lib,");
14795                    }
14796                    pw.print(name);
14797                    if (!checkin) {
14798                        pw.print(" -> ");
14799                    }
14800                    if (ent.path != null) {
14801                        if (!checkin) {
14802                            pw.print("(jar) ");
14803                            pw.print(ent.path);
14804                        } else {
14805                            pw.print(",jar,");
14806                            pw.print(ent.path);
14807                        }
14808                    } else {
14809                        if (!checkin) {
14810                            pw.print("(apk) ");
14811                            pw.print(ent.apk);
14812                        } else {
14813                            pw.print(",apk,");
14814                            pw.print(ent.apk);
14815                        }
14816                    }
14817                    pw.println();
14818                }
14819            }
14820
14821            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14822                if (dumpState.onTitlePrinted())
14823                    pw.println();
14824                if (!checkin) {
14825                    pw.println("Features:");
14826                }
14827                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14828                while (it.hasNext()) {
14829                    String name = it.next();
14830                    if (!checkin) {
14831                        pw.print("  ");
14832                    } else {
14833                        pw.print("feat,");
14834                    }
14835                    pw.println(name);
14836                }
14837            }
14838
14839            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14840                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14841                        : "Activity Resolver Table:", "  ", packageName,
14842                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14843                    dumpState.setTitlePrinted(true);
14844                }
14845                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14846                        : "Receiver Resolver Table:", "  ", packageName,
14847                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14848                    dumpState.setTitlePrinted(true);
14849                }
14850                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14851                        : "Service Resolver Table:", "  ", packageName,
14852                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14853                    dumpState.setTitlePrinted(true);
14854                }
14855                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14856                        : "Provider Resolver Table:", "  ", packageName,
14857                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14858                    dumpState.setTitlePrinted(true);
14859                }
14860            }
14861
14862            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14863                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14864                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14865                    int user = mSettings.mPreferredActivities.keyAt(i);
14866                    if (pir.dump(pw,
14867                            dumpState.getTitlePrinted()
14868                                ? "\nPreferred Activities User " + user + ":"
14869                                : "Preferred Activities User " + user + ":", "  ",
14870                            packageName, true, false)) {
14871                        dumpState.setTitlePrinted(true);
14872                    }
14873                }
14874            }
14875
14876            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14877                pw.flush();
14878                FileOutputStream fout = new FileOutputStream(fd);
14879                BufferedOutputStream str = new BufferedOutputStream(fout);
14880                XmlSerializer serializer = new FastXmlSerializer();
14881                try {
14882                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14883                    serializer.startDocument(null, true);
14884                    serializer.setFeature(
14885                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14886                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14887                    serializer.endDocument();
14888                    serializer.flush();
14889                } catch (IllegalArgumentException e) {
14890                    pw.println("Failed writing: " + e);
14891                } catch (IllegalStateException e) {
14892                    pw.println("Failed writing: " + e);
14893                } catch (IOException e) {
14894                    pw.println("Failed writing: " + e);
14895                }
14896            }
14897
14898            if (!checkin
14899                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14900                    && packageName == null) {
14901                pw.println();
14902                int count = mSettings.mPackages.size();
14903                if (count == 0) {
14904                    pw.println("No applications!");
14905                    pw.println();
14906                } else {
14907                    final String prefix = "  ";
14908                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14909                    if (allPackageSettings.size() == 0) {
14910                        pw.println("No domain preferred apps!");
14911                        pw.println();
14912                    } else {
14913                        pw.println("App verification status:");
14914                        pw.println();
14915                        count = 0;
14916                        for (PackageSetting ps : allPackageSettings) {
14917                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14918                            if (ivi == null || ivi.getPackageName() == null) continue;
14919                            pw.println(prefix + "Package: " + ivi.getPackageName());
14920                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14921                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14922                            pw.println();
14923                            count++;
14924                        }
14925                        if (count == 0) {
14926                            pw.println(prefix + "No app verification established.");
14927                            pw.println();
14928                        }
14929                        for (int userId : sUserManager.getUserIds()) {
14930                            pw.println("App linkages for user " + userId + ":");
14931                            pw.println();
14932                            count = 0;
14933                            for (PackageSetting ps : allPackageSettings) {
14934                                final long status = ps.getDomainVerificationStatusForUser(userId);
14935                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14936                                    continue;
14937                                }
14938                                pw.println(prefix + "Package: " + ps.name);
14939                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14940                                String statusStr = IntentFilterVerificationInfo.
14941                                        getStatusStringFromValue(status);
14942                                pw.println(prefix + "Status:  " + statusStr);
14943                                pw.println();
14944                                count++;
14945                            }
14946                            if (count == 0) {
14947                                pw.println(prefix + "No configured app linkages.");
14948                                pw.println();
14949                            }
14950                        }
14951                    }
14952                }
14953            }
14954
14955            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14956                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14957                if (packageName == null && permissionNames == null) {
14958                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14959                        if (iperm == 0) {
14960                            if (dumpState.onTitlePrinted())
14961                                pw.println();
14962                            pw.println("AppOp Permissions:");
14963                        }
14964                        pw.print("  AppOp Permission ");
14965                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14966                        pw.println(":");
14967                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14968                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14969                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14970                        }
14971                    }
14972                }
14973            }
14974
14975            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14976                boolean printedSomething = false;
14977                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14978                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14979                        continue;
14980                    }
14981                    if (!printedSomething) {
14982                        if (dumpState.onTitlePrinted())
14983                            pw.println();
14984                        pw.println("Registered ContentProviders:");
14985                        printedSomething = true;
14986                    }
14987                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14988                    pw.print("    "); pw.println(p.toString());
14989                }
14990                printedSomething = false;
14991                for (Map.Entry<String, PackageParser.Provider> entry :
14992                        mProvidersByAuthority.entrySet()) {
14993                    PackageParser.Provider p = entry.getValue();
14994                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14995                        continue;
14996                    }
14997                    if (!printedSomething) {
14998                        if (dumpState.onTitlePrinted())
14999                            pw.println();
15000                        pw.println("ContentProvider Authorities:");
15001                        printedSomething = true;
15002                    }
15003                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15004                    pw.print("    "); pw.println(p.toString());
15005                    if (p.info != null && p.info.applicationInfo != null) {
15006                        final String appInfo = p.info.applicationInfo.toString();
15007                        pw.print("      applicationInfo="); pw.println(appInfo);
15008                    }
15009                }
15010            }
15011
15012            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15013                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15014            }
15015
15016            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15017                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15018            }
15019
15020            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15021                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15022            }
15023
15024            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15025                // XXX should handle packageName != null by dumping only install data that
15026                // the given package is involved with.
15027                if (dumpState.onTitlePrinted()) pw.println();
15028                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15029            }
15030
15031            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15032                if (dumpState.onTitlePrinted()) pw.println();
15033                mSettings.dumpReadMessagesLPr(pw, dumpState);
15034
15035                pw.println();
15036                pw.println("Package warning messages:");
15037                BufferedReader in = null;
15038                String line = null;
15039                try {
15040                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15041                    while ((line = in.readLine()) != null) {
15042                        if (line.contains("ignored: updated version")) continue;
15043                        pw.println(line);
15044                    }
15045                } catch (IOException ignored) {
15046                } finally {
15047                    IoUtils.closeQuietly(in);
15048                }
15049            }
15050
15051            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15052                BufferedReader in = null;
15053                String line = null;
15054                try {
15055                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15056                    while ((line = in.readLine()) != null) {
15057                        if (line.contains("ignored: updated version")) continue;
15058                        pw.print("msg,");
15059                        pw.println(line);
15060                    }
15061                } catch (IOException ignored) {
15062                } finally {
15063                    IoUtils.closeQuietly(in);
15064                }
15065            }
15066        }
15067    }
15068
15069    private String dumpDomainString(String packageName) {
15070        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15071        List<IntentFilter> filters = getAllIntentFilters(packageName);
15072
15073        ArraySet<String> result = new ArraySet<>();
15074        if (iviList.size() > 0) {
15075            for (IntentFilterVerificationInfo ivi : iviList) {
15076                for (String host : ivi.getDomains()) {
15077                    result.add(host);
15078                }
15079            }
15080        }
15081        if (filters != null && filters.size() > 0) {
15082            for (IntentFilter filter : filters) {
15083                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15084                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15085                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15086                    result.addAll(filter.getHostsList());
15087                }
15088            }
15089        }
15090
15091        StringBuilder sb = new StringBuilder(result.size() * 16);
15092        for (String domain : result) {
15093            if (sb.length() > 0) sb.append(" ");
15094            sb.append(domain);
15095        }
15096        return sb.toString();
15097    }
15098
15099    // ------- apps on sdcard specific code -------
15100    static final boolean DEBUG_SD_INSTALL = false;
15101
15102    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15103
15104    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15105
15106    private boolean mMediaMounted = false;
15107
15108    static String getEncryptKey() {
15109        try {
15110            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15111                    SD_ENCRYPTION_KEYSTORE_NAME);
15112            if (sdEncKey == null) {
15113                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15114                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15115                if (sdEncKey == null) {
15116                    Slog.e(TAG, "Failed to create encryption keys");
15117                    return null;
15118                }
15119            }
15120            return sdEncKey;
15121        } catch (NoSuchAlgorithmException nsae) {
15122            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15123            return null;
15124        } catch (IOException ioe) {
15125            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15126            return null;
15127        }
15128    }
15129
15130    /*
15131     * Update media status on PackageManager.
15132     */
15133    @Override
15134    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15135        int callingUid = Binder.getCallingUid();
15136        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15137            throw new SecurityException("Media status can only be updated by the system");
15138        }
15139        // reader; this apparently protects mMediaMounted, but should probably
15140        // be a different lock in that case.
15141        synchronized (mPackages) {
15142            Log.i(TAG, "Updating external media status from "
15143                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15144                    + (mediaStatus ? "mounted" : "unmounted"));
15145            if (DEBUG_SD_INSTALL)
15146                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15147                        + ", mMediaMounted=" + mMediaMounted);
15148            if (mediaStatus == mMediaMounted) {
15149                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15150                        : 0, -1);
15151                mHandler.sendMessage(msg);
15152                return;
15153            }
15154            mMediaMounted = mediaStatus;
15155        }
15156        // Queue up an async operation since the package installation may take a
15157        // little while.
15158        mHandler.post(new Runnable() {
15159            public void run() {
15160                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15161            }
15162        });
15163    }
15164
15165    /**
15166     * Called by MountService when the initial ASECs to scan are available.
15167     * Should block until all the ASEC containers are finished being scanned.
15168     */
15169    public void scanAvailableAsecs() {
15170        updateExternalMediaStatusInner(true, false, false);
15171        if (mShouldRestoreconData) {
15172            SELinuxMMAC.setRestoreconDone();
15173            mShouldRestoreconData = false;
15174        }
15175    }
15176
15177    /*
15178     * Collect information of applications on external media, map them against
15179     * existing containers and update information based on current mount status.
15180     * Please note that we always have to report status if reportStatus has been
15181     * set to true especially when unloading packages.
15182     */
15183    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15184            boolean externalStorage) {
15185        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15186        int[] uidArr = EmptyArray.INT;
15187
15188        final String[] list = PackageHelper.getSecureContainerList();
15189        if (ArrayUtils.isEmpty(list)) {
15190            Log.i(TAG, "No secure containers found");
15191        } else {
15192            // Process list of secure containers and categorize them
15193            // as active or stale based on their package internal state.
15194
15195            // reader
15196            synchronized (mPackages) {
15197                for (String cid : list) {
15198                    // Leave stages untouched for now; installer service owns them
15199                    if (PackageInstallerService.isStageName(cid)) continue;
15200
15201                    if (DEBUG_SD_INSTALL)
15202                        Log.i(TAG, "Processing container " + cid);
15203                    String pkgName = getAsecPackageName(cid);
15204                    if (pkgName == null) {
15205                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15206                        continue;
15207                    }
15208                    if (DEBUG_SD_INSTALL)
15209                        Log.i(TAG, "Looking for pkg : " + pkgName);
15210
15211                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15212                    if (ps == null) {
15213                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15214                        continue;
15215                    }
15216
15217                    /*
15218                     * Skip packages that are not external if we're unmounting
15219                     * external storage.
15220                     */
15221                    if (externalStorage && !isMounted && !isExternal(ps)) {
15222                        continue;
15223                    }
15224
15225                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15226                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15227                    // The package status is changed only if the code path
15228                    // matches between settings and the container id.
15229                    if (ps.codePathString != null
15230                            && ps.codePathString.startsWith(args.getCodePath())) {
15231                        if (DEBUG_SD_INSTALL) {
15232                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15233                                    + " at code path: " + ps.codePathString);
15234                        }
15235
15236                        // We do have a valid package installed on sdcard
15237                        processCids.put(args, ps.codePathString);
15238                        final int uid = ps.appId;
15239                        if (uid != -1) {
15240                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15241                        }
15242                    } else {
15243                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15244                                + ps.codePathString);
15245                    }
15246                }
15247            }
15248
15249            Arrays.sort(uidArr);
15250        }
15251
15252        // Process packages with valid entries.
15253        if (isMounted) {
15254            if (DEBUG_SD_INSTALL)
15255                Log.i(TAG, "Loading packages");
15256            loadMediaPackages(processCids, uidArr);
15257            startCleaningPackages();
15258            mInstallerService.onSecureContainersAvailable();
15259        } else {
15260            if (DEBUG_SD_INSTALL)
15261                Log.i(TAG, "Unloading packages");
15262            unloadMediaPackages(processCids, uidArr, reportStatus);
15263        }
15264    }
15265
15266    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15267            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15268        final int size = infos.size();
15269        final String[] packageNames = new String[size];
15270        final int[] packageUids = new int[size];
15271        for (int i = 0; i < size; i++) {
15272            final ApplicationInfo info = infos.get(i);
15273            packageNames[i] = info.packageName;
15274            packageUids[i] = info.uid;
15275        }
15276        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15277                finishedReceiver);
15278    }
15279
15280    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15281            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15282        sendResourcesChangedBroadcast(mediaStatus, replacing,
15283                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15284    }
15285
15286    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15287            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15288        int size = pkgList.length;
15289        if (size > 0) {
15290            // Send broadcasts here
15291            Bundle extras = new Bundle();
15292            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15293            if (uidArr != null) {
15294                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15295            }
15296            if (replacing) {
15297                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15298            }
15299            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15300                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15301            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15302        }
15303    }
15304
15305   /*
15306     * Look at potentially valid container ids from processCids If package
15307     * information doesn't match the one on record or package scanning fails,
15308     * the cid is added to list of removeCids. We currently don't delete stale
15309     * containers.
15310     */
15311    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15312        ArrayList<String> pkgList = new ArrayList<String>();
15313        Set<AsecInstallArgs> keys = processCids.keySet();
15314
15315        for (AsecInstallArgs args : keys) {
15316            String codePath = processCids.get(args);
15317            if (DEBUG_SD_INSTALL)
15318                Log.i(TAG, "Loading container : " + args.cid);
15319            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15320            try {
15321                // Make sure there are no container errors first.
15322                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15323                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15324                            + " when installing from sdcard");
15325                    continue;
15326                }
15327                // Check code path here.
15328                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15329                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15330                            + " does not match one in settings " + codePath);
15331                    continue;
15332                }
15333                // Parse package
15334                int parseFlags = mDefParseFlags;
15335                if (args.isExternalAsec()) {
15336                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15337                }
15338                if (args.isFwdLocked()) {
15339                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15340                }
15341
15342                synchronized (mInstallLock) {
15343                    PackageParser.Package pkg = null;
15344                    try {
15345                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15346                    } catch (PackageManagerException e) {
15347                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15348                    }
15349                    // Scan the package
15350                    if (pkg != null) {
15351                        /*
15352                         * TODO why is the lock being held? doPostInstall is
15353                         * called in other places without the lock. This needs
15354                         * to be straightened out.
15355                         */
15356                        // writer
15357                        synchronized (mPackages) {
15358                            retCode = PackageManager.INSTALL_SUCCEEDED;
15359                            pkgList.add(pkg.packageName);
15360                            // Post process args
15361                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15362                                    pkg.applicationInfo.uid);
15363                        }
15364                    } else {
15365                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15366                    }
15367                }
15368
15369            } finally {
15370                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15371                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15372                }
15373            }
15374        }
15375        // writer
15376        synchronized (mPackages) {
15377            // If the platform SDK has changed since the last time we booted,
15378            // we need to re-grant app permission to catch any new ones that
15379            // appear. This is really a hack, and means that apps can in some
15380            // cases get permissions that the user didn't initially explicitly
15381            // allow... it would be nice to have some better way to handle
15382            // this situation.
15383            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15384            if (regrantPermissions)
15385                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15386                        + mSdkVersion + "; regranting permissions for external storage");
15387            mSettings.mExternalSdkPlatform = mSdkVersion;
15388
15389            // Make sure group IDs have been assigned, and any permission
15390            // changes in other apps are accounted for
15391            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15392                    | (regrantPermissions
15393                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15394                            : 0));
15395
15396            mSettings.updateExternalDatabaseVersion();
15397
15398            // can downgrade to reader
15399            // Persist settings
15400            mSettings.writeLPr();
15401        }
15402        // Send a broadcast to let everyone know we are done processing
15403        if (pkgList.size() > 0) {
15404            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15405        }
15406    }
15407
15408   /*
15409     * Utility method to unload a list of specified containers
15410     */
15411    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15412        // Just unmount all valid containers.
15413        for (AsecInstallArgs arg : cidArgs) {
15414            synchronized (mInstallLock) {
15415                arg.doPostDeleteLI(false);
15416           }
15417       }
15418   }
15419
15420    /*
15421     * Unload packages mounted on external media. This involves deleting package
15422     * data from internal structures, sending broadcasts about diabled packages,
15423     * gc'ing to free up references, unmounting all secure containers
15424     * corresponding to packages on external media, and posting a
15425     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15426     * that we always have to post this message if status has been requested no
15427     * matter what.
15428     */
15429    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15430            final boolean reportStatus) {
15431        if (DEBUG_SD_INSTALL)
15432            Log.i(TAG, "unloading media packages");
15433        ArrayList<String> pkgList = new ArrayList<String>();
15434        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15435        final Set<AsecInstallArgs> keys = processCids.keySet();
15436        for (AsecInstallArgs args : keys) {
15437            String pkgName = args.getPackageName();
15438            if (DEBUG_SD_INSTALL)
15439                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15440            // Delete package internally
15441            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15442            synchronized (mInstallLock) {
15443                boolean res = deletePackageLI(pkgName, null, false, null, null,
15444                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15445                if (res) {
15446                    pkgList.add(pkgName);
15447                } else {
15448                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15449                    failedList.add(args);
15450                }
15451            }
15452        }
15453
15454        // reader
15455        synchronized (mPackages) {
15456            // We didn't update the settings after removing each package;
15457            // write them now for all packages.
15458            mSettings.writeLPr();
15459        }
15460
15461        // We have to absolutely send UPDATED_MEDIA_STATUS only
15462        // after confirming that all the receivers processed the ordered
15463        // broadcast when packages get disabled, force a gc to clean things up.
15464        // and unload all the containers.
15465        if (pkgList.size() > 0) {
15466            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15467                    new IIntentReceiver.Stub() {
15468                public void performReceive(Intent intent, int resultCode, String data,
15469                        Bundle extras, boolean ordered, boolean sticky,
15470                        int sendingUser) throws RemoteException {
15471                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15472                            reportStatus ? 1 : 0, 1, keys);
15473                    mHandler.sendMessage(msg);
15474                }
15475            });
15476        } else {
15477            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15478                    keys);
15479            mHandler.sendMessage(msg);
15480        }
15481    }
15482
15483    private void loadPrivatePackages(VolumeInfo vol) {
15484        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15485        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15486        synchronized (mInstallLock) {
15487        synchronized (mPackages) {
15488            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15489            for (PackageSetting ps : packages) {
15490                final PackageParser.Package pkg;
15491                try {
15492                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15493                    loaded.add(pkg.applicationInfo);
15494                } catch (PackageManagerException e) {
15495                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15496                }
15497            }
15498
15499            // TODO: regrant any permissions that changed based since original install
15500
15501            mSettings.writeLPr();
15502        }
15503        }
15504
15505        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15506        sendResourcesChangedBroadcast(true, false, loaded, null);
15507    }
15508
15509    private void unloadPrivatePackages(VolumeInfo vol) {
15510        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15511        synchronized (mInstallLock) {
15512        synchronized (mPackages) {
15513            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15514            for (PackageSetting ps : packages) {
15515                if (ps.pkg == null) continue;
15516
15517                final ApplicationInfo info = ps.pkg.applicationInfo;
15518                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15519                if (deletePackageLI(ps.name, null, false, null, null,
15520                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15521                    unloaded.add(info);
15522                } else {
15523                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15524                }
15525            }
15526
15527            mSettings.writeLPr();
15528        }
15529        }
15530
15531        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15532        sendResourcesChangedBroadcast(false, false, unloaded, null);
15533    }
15534
15535    /**
15536     * Examine all users present on given mounted volume, and destroy data
15537     * belonging to users that are no longer valid, or whose user ID has been
15538     * recycled.
15539     */
15540    private void reconcileUsers(String volumeUuid) {
15541        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15542        if (ArrayUtils.isEmpty(files)) {
15543            Slog.d(TAG, "No users found on " + volumeUuid);
15544            return;
15545        }
15546
15547        for (File file : files) {
15548            if (!file.isDirectory()) continue;
15549
15550            final int userId;
15551            final UserInfo info;
15552            try {
15553                userId = Integer.parseInt(file.getName());
15554                info = sUserManager.getUserInfo(userId);
15555            } catch (NumberFormatException e) {
15556                Slog.w(TAG, "Invalid user directory " + file);
15557                continue;
15558            }
15559
15560            boolean destroyUser = false;
15561            if (info == null) {
15562                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15563                        + " because no matching user was found");
15564                destroyUser = true;
15565            } else {
15566                try {
15567                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15568                } catch (IOException e) {
15569                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15570                            + " because we failed to enforce serial number: " + e);
15571                    destroyUser = true;
15572                }
15573            }
15574
15575            if (destroyUser) {
15576                synchronized (mInstallLock) {
15577                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15578                }
15579            }
15580        }
15581
15582        final UserManager um = mContext.getSystemService(UserManager.class);
15583        for (UserInfo user : um.getUsers()) {
15584            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15585            if (userDir.exists()) continue;
15586
15587            try {
15588                UserManagerService.prepareUserDirectory(userDir);
15589                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15590            } catch (IOException e) {
15591                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15592            }
15593        }
15594    }
15595
15596    /**
15597     * Examine all apps present on given mounted volume, and destroy apps that
15598     * aren't expected, either due to uninstallation or reinstallation on
15599     * another volume.
15600     */
15601    private void reconcileApps(String volumeUuid) {
15602        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15603        if (ArrayUtils.isEmpty(files)) {
15604            Slog.d(TAG, "No apps found on " + volumeUuid);
15605            return;
15606        }
15607
15608        for (File file : files) {
15609            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15610                    && !PackageInstallerService.isStageName(file.getName());
15611            if (!isPackage) {
15612                // Ignore entries which are not packages
15613                continue;
15614            }
15615
15616            boolean destroyApp = false;
15617            String packageName = null;
15618            try {
15619                final PackageLite pkg = PackageParser.parsePackageLite(file,
15620                        PackageParser.PARSE_MUST_BE_APK);
15621                packageName = pkg.packageName;
15622
15623                synchronized (mPackages) {
15624                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15625                    if (ps == null) {
15626                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15627                                + volumeUuid + " because we found no install record");
15628                        destroyApp = true;
15629                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15630                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15631                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15632                        destroyApp = true;
15633                    }
15634                }
15635
15636            } catch (PackageParserException e) {
15637                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15638                destroyApp = true;
15639            }
15640
15641            if (destroyApp) {
15642                synchronized (mInstallLock) {
15643                    if (packageName != null) {
15644                        removeDataDirsLI(volumeUuid, packageName);
15645                    }
15646                    if (file.isDirectory()) {
15647                        mInstaller.rmPackageDir(file.getAbsolutePath());
15648                    } else {
15649                        file.delete();
15650                    }
15651                }
15652            }
15653        }
15654    }
15655
15656    private void unfreezePackage(String packageName) {
15657        synchronized (mPackages) {
15658            final PackageSetting ps = mSettings.mPackages.get(packageName);
15659            if (ps != null) {
15660                ps.frozen = false;
15661            }
15662        }
15663    }
15664
15665    @Override
15666    public int movePackage(final String packageName, final String volumeUuid) {
15667        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15668
15669        final int moveId = mNextMoveId.getAndIncrement();
15670        try {
15671            movePackageInternal(packageName, volumeUuid, moveId);
15672        } catch (PackageManagerException e) {
15673            Slog.w(TAG, "Failed to move " + packageName, e);
15674            mMoveCallbacks.notifyStatusChanged(moveId,
15675                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15676        }
15677        return moveId;
15678    }
15679
15680    private void movePackageInternal(final String packageName, final String volumeUuid,
15681            final int moveId) throws PackageManagerException {
15682        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15683        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15684        final PackageManager pm = mContext.getPackageManager();
15685
15686        final boolean currentAsec;
15687        final String currentVolumeUuid;
15688        final File codeFile;
15689        final String installerPackageName;
15690        final String packageAbiOverride;
15691        final int appId;
15692        final String seinfo;
15693        final String label;
15694
15695        // reader
15696        synchronized (mPackages) {
15697            final PackageParser.Package pkg = mPackages.get(packageName);
15698            final PackageSetting ps = mSettings.mPackages.get(packageName);
15699            if (pkg == null || ps == null) {
15700                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15701            }
15702
15703            if (pkg.applicationInfo.isSystemApp()) {
15704                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15705                        "Cannot move system application");
15706            }
15707
15708            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15709                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15710                        "Package already moved to " + volumeUuid);
15711            }
15712
15713            final File probe = new File(pkg.codePath);
15714            final File probeOat = new File(probe, "oat");
15715            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15716                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15717                        "Move only supported for modern cluster style installs");
15718            }
15719
15720            if (ps.frozen) {
15721                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15722                        "Failed to move already frozen package");
15723            }
15724            ps.frozen = true;
15725
15726            currentAsec = pkg.applicationInfo.isForwardLocked()
15727                    || pkg.applicationInfo.isExternalAsec();
15728            currentVolumeUuid = ps.volumeUuid;
15729            codeFile = new File(pkg.codePath);
15730            installerPackageName = ps.installerPackageName;
15731            packageAbiOverride = ps.cpuAbiOverrideString;
15732            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15733            seinfo = pkg.applicationInfo.seinfo;
15734            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15735        }
15736
15737        // Now that we're guarded by frozen state, kill app during move
15738        killApplication(packageName, appId, "move pkg");
15739
15740        final Bundle extras = new Bundle();
15741        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15742        extras.putString(Intent.EXTRA_TITLE, label);
15743        mMoveCallbacks.notifyCreated(moveId, extras);
15744
15745        int installFlags;
15746        final boolean moveCompleteApp;
15747        final File measurePath;
15748
15749        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15750            installFlags = INSTALL_INTERNAL;
15751            moveCompleteApp = !currentAsec;
15752            measurePath = Environment.getDataAppDirectory(volumeUuid);
15753        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15754            installFlags = INSTALL_EXTERNAL;
15755            moveCompleteApp = false;
15756            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15757        } else {
15758            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15759            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15760                    || !volume.isMountedWritable()) {
15761                unfreezePackage(packageName);
15762                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15763                        "Move location not mounted private volume");
15764            }
15765
15766            Preconditions.checkState(!currentAsec);
15767
15768            installFlags = INSTALL_INTERNAL;
15769            moveCompleteApp = true;
15770            measurePath = Environment.getDataAppDirectory(volumeUuid);
15771        }
15772
15773        final PackageStats stats = new PackageStats(null, -1);
15774        synchronized (mInstaller) {
15775            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15776                unfreezePackage(packageName);
15777                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15778                        "Failed to measure package size");
15779            }
15780        }
15781
15782        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15783                + stats.dataSize);
15784
15785        final long startFreeBytes = measurePath.getFreeSpace();
15786        final long sizeBytes;
15787        if (moveCompleteApp) {
15788            sizeBytes = stats.codeSize + stats.dataSize;
15789        } else {
15790            sizeBytes = stats.codeSize;
15791        }
15792
15793        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15794            unfreezePackage(packageName);
15795            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15796                    "Not enough free space to move");
15797        }
15798
15799        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15800
15801        final CountDownLatch installedLatch = new CountDownLatch(1);
15802        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15803            @Override
15804            public void onUserActionRequired(Intent intent) throws RemoteException {
15805                throw new IllegalStateException();
15806            }
15807
15808            @Override
15809            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15810                    Bundle extras) throws RemoteException {
15811                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15812                        + PackageManager.installStatusToString(returnCode, msg));
15813
15814                installedLatch.countDown();
15815
15816                // Regardless of success or failure of the move operation,
15817                // always unfreeze the package
15818                unfreezePackage(packageName);
15819
15820                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15821                switch (status) {
15822                    case PackageInstaller.STATUS_SUCCESS:
15823                        mMoveCallbacks.notifyStatusChanged(moveId,
15824                                PackageManager.MOVE_SUCCEEDED);
15825                        break;
15826                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15827                        mMoveCallbacks.notifyStatusChanged(moveId,
15828                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15829                        break;
15830                    default:
15831                        mMoveCallbacks.notifyStatusChanged(moveId,
15832                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15833                        break;
15834                }
15835            }
15836        };
15837
15838        final MoveInfo move;
15839        if (moveCompleteApp) {
15840            // Kick off a thread to report progress estimates
15841            new Thread() {
15842                @Override
15843                public void run() {
15844                    while (true) {
15845                        try {
15846                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15847                                break;
15848                            }
15849                        } catch (InterruptedException ignored) {
15850                        }
15851
15852                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15853                        final int progress = 10 + (int) MathUtils.constrain(
15854                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15855                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15856                    }
15857                }
15858            }.start();
15859
15860            final String dataAppName = codeFile.getName();
15861            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15862                    dataAppName, appId, seinfo);
15863        } else {
15864            move = null;
15865        }
15866
15867        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15868
15869        final Message msg = mHandler.obtainMessage(INIT_COPY);
15870        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15871        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15872                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15873        mHandler.sendMessage(msg);
15874    }
15875
15876    @Override
15877    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15878        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15879
15880        final int realMoveId = mNextMoveId.getAndIncrement();
15881        final Bundle extras = new Bundle();
15882        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15883        mMoveCallbacks.notifyCreated(realMoveId, extras);
15884
15885        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15886            @Override
15887            public void onCreated(int moveId, Bundle extras) {
15888                // Ignored
15889            }
15890
15891            @Override
15892            public void onStatusChanged(int moveId, int status, long estMillis) {
15893                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15894            }
15895        };
15896
15897        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15898        storage.setPrimaryStorageUuid(volumeUuid, callback);
15899        return realMoveId;
15900    }
15901
15902    @Override
15903    public int getMoveStatus(int moveId) {
15904        mContext.enforceCallingOrSelfPermission(
15905                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15906        return mMoveCallbacks.mLastStatus.get(moveId);
15907    }
15908
15909    @Override
15910    public void registerMoveCallback(IPackageMoveObserver callback) {
15911        mContext.enforceCallingOrSelfPermission(
15912                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15913        mMoveCallbacks.register(callback);
15914    }
15915
15916    @Override
15917    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15918        mContext.enforceCallingOrSelfPermission(
15919                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15920        mMoveCallbacks.unregister(callback);
15921    }
15922
15923    @Override
15924    public boolean setInstallLocation(int loc) {
15925        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15926                null);
15927        if (getInstallLocation() == loc) {
15928            return true;
15929        }
15930        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15931                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15932            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15933                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15934            return true;
15935        }
15936        return false;
15937   }
15938
15939    @Override
15940    public int getInstallLocation() {
15941        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15942                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15943                PackageHelper.APP_INSTALL_AUTO);
15944    }
15945
15946    /** Called by UserManagerService */
15947    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15948        mDirtyUsers.remove(userHandle);
15949        mSettings.removeUserLPw(userHandle);
15950        mPendingBroadcasts.remove(userHandle);
15951        if (mInstaller != null) {
15952            // Technically, we shouldn't be doing this with the package lock
15953            // held.  However, this is very rare, and there is already so much
15954            // other disk I/O going on, that we'll let it slide for now.
15955            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15956            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15957                final String volumeUuid = vol.getFsUuid();
15958                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15959                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15960            }
15961        }
15962        mUserNeedsBadging.delete(userHandle);
15963        removeUnusedPackagesLILPw(userManager, userHandle);
15964    }
15965
15966    /**
15967     * We're removing userHandle and would like to remove any downloaded packages
15968     * that are no longer in use by any other user.
15969     * @param userHandle the user being removed
15970     */
15971    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15972        final boolean DEBUG_CLEAN_APKS = false;
15973        int [] users = userManager.getUserIdsLPr();
15974        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15975        while (psit.hasNext()) {
15976            PackageSetting ps = psit.next();
15977            if (ps.pkg == null) {
15978                continue;
15979            }
15980            final String packageName = ps.pkg.packageName;
15981            // Skip over if system app
15982            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15983                continue;
15984            }
15985            if (DEBUG_CLEAN_APKS) {
15986                Slog.i(TAG, "Checking package " + packageName);
15987            }
15988            boolean keep = false;
15989            for (int i = 0; i < users.length; i++) {
15990                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15991                    keep = true;
15992                    if (DEBUG_CLEAN_APKS) {
15993                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15994                                + users[i]);
15995                    }
15996                    break;
15997                }
15998            }
15999            if (!keep) {
16000                if (DEBUG_CLEAN_APKS) {
16001                    Slog.i(TAG, "  Removing package " + packageName);
16002                }
16003                mHandler.post(new Runnable() {
16004                    public void run() {
16005                        deletePackageX(packageName, userHandle, 0);
16006                    } //end run
16007                });
16008            }
16009        }
16010    }
16011
16012    /** Called by UserManagerService */
16013    void createNewUserLILPw(int userHandle) {
16014        if (mInstaller != null) {
16015            mInstaller.createUserConfig(userHandle);
16016            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16017            applyFactoryDefaultBrowserLPw(userHandle);
16018            primeDomainVerificationsLPw(userHandle);
16019        }
16020    }
16021
16022    void newUserCreated(final int userHandle) {
16023        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16024    }
16025
16026    @Override
16027    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16028        mContext.enforceCallingOrSelfPermission(
16029                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16030                "Only package verification agents can read the verifier device identity");
16031
16032        synchronized (mPackages) {
16033            return mSettings.getVerifierDeviceIdentityLPw();
16034        }
16035    }
16036
16037    @Override
16038    public void setPermissionEnforced(String permission, boolean enforced) {
16039        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16040        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16041            synchronized (mPackages) {
16042                if (mSettings.mReadExternalStorageEnforced == null
16043                        || mSettings.mReadExternalStorageEnforced != enforced) {
16044                    mSettings.mReadExternalStorageEnforced = enforced;
16045                    mSettings.writeLPr();
16046                }
16047            }
16048            // kill any non-foreground processes so we restart them and
16049            // grant/revoke the GID.
16050            final IActivityManager am = ActivityManagerNative.getDefault();
16051            if (am != null) {
16052                final long token = Binder.clearCallingIdentity();
16053                try {
16054                    am.killProcessesBelowForeground("setPermissionEnforcement");
16055                } catch (RemoteException e) {
16056                } finally {
16057                    Binder.restoreCallingIdentity(token);
16058                }
16059            }
16060        } else {
16061            throw new IllegalArgumentException("No selective enforcement for " + permission);
16062        }
16063    }
16064
16065    @Override
16066    @Deprecated
16067    public boolean isPermissionEnforced(String permission) {
16068        return true;
16069    }
16070
16071    @Override
16072    public boolean isStorageLow() {
16073        final long token = Binder.clearCallingIdentity();
16074        try {
16075            final DeviceStorageMonitorInternal
16076                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16077            if (dsm != null) {
16078                return dsm.isMemoryLow();
16079            } else {
16080                return false;
16081            }
16082        } finally {
16083            Binder.restoreCallingIdentity(token);
16084        }
16085    }
16086
16087    @Override
16088    public IPackageInstaller getPackageInstaller() {
16089        return mInstallerService;
16090    }
16091
16092    private boolean userNeedsBadging(int userId) {
16093        int index = mUserNeedsBadging.indexOfKey(userId);
16094        if (index < 0) {
16095            final UserInfo userInfo;
16096            final long token = Binder.clearCallingIdentity();
16097            try {
16098                userInfo = sUserManager.getUserInfo(userId);
16099            } finally {
16100                Binder.restoreCallingIdentity(token);
16101            }
16102            final boolean b;
16103            if (userInfo != null && userInfo.isManagedProfile()) {
16104                b = true;
16105            } else {
16106                b = false;
16107            }
16108            mUserNeedsBadging.put(userId, b);
16109            return b;
16110        }
16111        return mUserNeedsBadging.valueAt(index);
16112    }
16113
16114    @Override
16115    public KeySet getKeySetByAlias(String packageName, String alias) {
16116        if (packageName == null || alias == null) {
16117            return null;
16118        }
16119        synchronized(mPackages) {
16120            final PackageParser.Package pkg = mPackages.get(packageName);
16121            if (pkg == null) {
16122                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16123                throw new IllegalArgumentException("Unknown package: " + packageName);
16124            }
16125            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16126            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16127        }
16128    }
16129
16130    @Override
16131    public KeySet getSigningKeySet(String packageName) {
16132        if (packageName == null) {
16133            return null;
16134        }
16135        synchronized(mPackages) {
16136            final PackageParser.Package pkg = mPackages.get(packageName);
16137            if (pkg == null) {
16138                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16139                throw new IllegalArgumentException("Unknown package: " + packageName);
16140            }
16141            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16142                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16143                throw new SecurityException("May not access signing KeySet of other apps.");
16144            }
16145            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16146            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16147        }
16148    }
16149
16150    @Override
16151    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16152        if (packageName == null || ks == null) {
16153            return false;
16154        }
16155        synchronized(mPackages) {
16156            final PackageParser.Package pkg = mPackages.get(packageName);
16157            if (pkg == null) {
16158                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16159                throw new IllegalArgumentException("Unknown package: " + packageName);
16160            }
16161            IBinder ksh = ks.getToken();
16162            if (ksh instanceof KeySetHandle) {
16163                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16164                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16165            }
16166            return false;
16167        }
16168    }
16169
16170    @Override
16171    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16172        if (packageName == null || ks == null) {
16173            return false;
16174        }
16175        synchronized(mPackages) {
16176            final PackageParser.Package pkg = mPackages.get(packageName);
16177            if (pkg == null) {
16178                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16179                throw new IllegalArgumentException("Unknown package: " + packageName);
16180            }
16181            IBinder ksh = ks.getToken();
16182            if (ksh instanceof KeySetHandle) {
16183                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16184                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16185            }
16186            return false;
16187        }
16188    }
16189
16190    public void getUsageStatsIfNoPackageUsageInfo() {
16191        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16192            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16193            if (usm == null) {
16194                throw new IllegalStateException("UsageStatsManager must be initialized");
16195            }
16196            long now = System.currentTimeMillis();
16197            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16198            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16199                String packageName = entry.getKey();
16200                PackageParser.Package pkg = mPackages.get(packageName);
16201                if (pkg == null) {
16202                    continue;
16203                }
16204                UsageStats usage = entry.getValue();
16205                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16206                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16207            }
16208        }
16209    }
16210
16211    /**
16212     * Check and throw if the given before/after packages would be considered a
16213     * downgrade.
16214     */
16215    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16216            throws PackageManagerException {
16217        if (after.versionCode < before.mVersionCode) {
16218            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16219                    "Update version code " + after.versionCode + " is older than current "
16220                    + before.mVersionCode);
16221        } else if (after.versionCode == before.mVersionCode) {
16222            if (after.baseRevisionCode < before.baseRevisionCode) {
16223                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16224                        "Update base revision code " + after.baseRevisionCode
16225                        + " is older than current " + before.baseRevisionCode);
16226            }
16227
16228            if (!ArrayUtils.isEmpty(after.splitNames)) {
16229                for (int i = 0; i < after.splitNames.length; i++) {
16230                    final String splitName = after.splitNames[i];
16231                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16232                    if (j != -1) {
16233                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16234                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16235                                    "Update split " + splitName + " revision code "
16236                                    + after.splitRevisionCodes[i] + " is older than current "
16237                                    + before.splitRevisionCodes[j]);
16238                        }
16239                    }
16240                }
16241            }
16242        }
16243    }
16244
16245    private static class MoveCallbacks extends Handler {
16246        private static final int MSG_CREATED = 1;
16247        private static final int MSG_STATUS_CHANGED = 2;
16248
16249        private final RemoteCallbackList<IPackageMoveObserver>
16250                mCallbacks = new RemoteCallbackList<>();
16251
16252        private final SparseIntArray mLastStatus = new SparseIntArray();
16253
16254        public MoveCallbacks(Looper looper) {
16255            super(looper);
16256        }
16257
16258        public void register(IPackageMoveObserver callback) {
16259            mCallbacks.register(callback);
16260        }
16261
16262        public void unregister(IPackageMoveObserver callback) {
16263            mCallbacks.unregister(callback);
16264        }
16265
16266        @Override
16267        public void handleMessage(Message msg) {
16268            final SomeArgs args = (SomeArgs) msg.obj;
16269            final int n = mCallbacks.beginBroadcast();
16270            for (int i = 0; i < n; i++) {
16271                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16272                try {
16273                    invokeCallback(callback, msg.what, args);
16274                } catch (RemoteException ignored) {
16275                }
16276            }
16277            mCallbacks.finishBroadcast();
16278            args.recycle();
16279        }
16280
16281        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16282                throws RemoteException {
16283            switch (what) {
16284                case MSG_CREATED: {
16285                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16286                    break;
16287                }
16288                case MSG_STATUS_CHANGED: {
16289                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16290                    break;
16291                }
16292            }
16293        }
16294
16295        private void notifyCreated(int moveId, Bundle extras) {
16296            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16297
16298            final SomeArgs args = SomeArgs.obtain();
16299            args.argi1 = moveId;
16300            args.arg2 = extras;
16301            obtainMessage(MSG_CREATED, args).sendToTarget();
16302        }
16303
16304        private void notifyStatusChanged(int moveId, int status) {
16305            notifyStatusChanged(moveId, status, -1);
16306        }
16307
16308        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16309            Slog.v(TAG, "Move " + moveId + " status " + status);
16310
16311            final SomeArgs args = SomeArgs.obtain();
16312            args.argi1 = moveId;
16313            args.argi2 = status;
16314            args.arg3 = estMillis;
16315            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16316
16317            synchronized (mLastStatus) {
16318                mLastStatus.put(moveId, status);
16319            }
16320        }
16321    }
16322
16323    private final class OnPermissionChangeListeners extends Handler {
16324        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16325
16326        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16327                new RemoteCallbackList<>();
16328
16329        public OnPermissionChangeListeners(Looper looper) {
16330            super(looper);
16331        }
16332
16333        @Override
16334        public void handleMessage(Message msg) {
16335            switch (msg.what) {
16336                case MSG_ON_PERMISSIONS_CHANGED: {
16337                    final int uid = msg.arg1;
16338                    handleOnPermissionsChanged(uid);
16339                } break;
16340            }
16341        }
16342
16343        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16344            mPermissionListeners.register(listener);
16345
16346        }
16347
16348        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16349            mPermissionListeners.unregister(listener);
16350        }
16351
16352        public void onPermissionsChanged(int uid) {
16353            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16354                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16355            }
16356        }
16357
16358        private void handleOnPermissionsChanged(int uid) {
16359            final int count = mPermissionListeners.beginBroadcast();
16360            try {
16361                for (int i = 0; i < count; i++) {
16362                    IOnPermissionsChangeListener callback = mPermissionListeners
16363                            .getBroadcastItem(i);
16364                    try {
16365                        callback.onPermissionsChanged(uid);
16366                    } catch (RemoteException e) {
16367                        Log.e(TAG, "Permission listener is dead", e);
16368                    }
16369                }
16370            } finally {
16371                mPermissionListeners.finishBroadcast();
16372            }
16373        }
16374    }
16375
16376    private class PackageManagerInternalImpl extends PackageManagerInternal {
16377        @Override
16378        public void setLocationPackagesProvider(PackagesProvider provider) {
16379            synchronized (mPackages) {
16380                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16381            }
16382        }
16383
16384        @Override
16385        public void setImePackagesProvider(PackagesProvider provider) {
16386            synchronized (mPackages) {
16387                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16388            }
16389        }
16390
16391        @Override
16392        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16393            synchronized (mPackages) {
16394                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16395            }
16396        }
16397
16398        @Override
16399        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16400            synchronized (mPackages) {
16401                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16402            }
16403        }
16404
16405        @Override
16406        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16407            synchronized (mPackages) {
16408                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16409            }
16410        }
16411
16412        @Override
16413        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16414            synchronized (mPackages) {
16415                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16416            }
16417        }
16418
16419        @Override
16420        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16421            synchronized (mPackages) {
16422                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16423                        packageName, userId);
16424            }
16425        }
16426
16427        @Override
16428        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16429            synchronized (mPackages) {
16430                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16431                        packageName, userId);
16432            }
16433        }
16434    }
16435
16436    @Override
16437    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16438        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16439        synchronized (mPackages) {
16440            final long identity = Binder.clearCallingIdentity();
16441            try {
16442                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16443                        packageNames, userId);
16444            } finally {
16445                Binder.restoreCallingIdentity(identity);
16446            }
16447        }
16448    }
16449
16450    private static void enforceSystemOrPhoneCaller(String tag) {
16451        int callingUid = Binder.getCallingUid();
16452        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16453            throw new SecurityException(
16454                    "Cannot call " + tag + " from UID " + callingUid);
16455        }
16456    }
16457}
16458