PackageManagerService.java revision 7121e18595d4c559044e26bfe6035406a862f466
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.storage.DeviceStorageMonitorInternal;
228
229import org.xmlpull.v1.XmlPullParser;
230import org.xmlpull.v1.XmlPullParserException;
231import org.xmlpull.v1.XmlSerializer;
232
233import java.io.BufferedInputStream;
234import java.io.BufferedOutputStream;
235import java.io.BufferedReader;
236import java.io.ByteArrayInputStream;
237import java.io.ByteArrayOutputStream;
238import java.io.File;
239import java.io.FileDescriptor;
240import java.io.FileNotFoundException;
241import java.io.FileOutputStream;
242import java.io.FileReader;
243import java.io.FilenameFilter;
244import java.io.IOException;
245import java.io.InputStream;
246import java.io.PrintWriter;
247import java.nio.charset.StandardCharsets;
248import java.security.NoSuchAlgorithmException;
249import java.security.PublicKey;
250import java.security.cert.CertificateEncodingException;
251import java.security.cert.CertificateException;
252import java.text.SimpleDateFormat;
253import java.util.ArrayList;
254import java.util.Arrays;
255import java.util.Collection;
256import java.util.Collections;
257import java.util.Comparator;
258import java.util.Date;
259import java.util.Iterator;
260import java.util.List;
261import java.util.Map;
262import java.util.Objects;
263import java.util.Set;
264import java.util.concurrent.CountDownLatch;
265import java.util.concurrent.TimeUnit;
266import java.util.concurrent.atomic.AtomicBoolean;
267import java.util.concurrent.atomic.AtomicInteger;
268import java.util.concurrent.atomic.AtomicLong;
269
270/**
271 * Keep track of all those .apks everywhere.
272 *
273 * This is very central to the platform's security; please run the unit
274 * tests whenever making modifications here:
275 *
276mmm frameworks/base/tests/AndroidTests
277adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
278adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
279 *
280 * {@hide}
281 */
282public class PackageManagerService extends IPackageManager.Stub {
283    static final String TAG = "PackageManager";
284    static final boolean DEBUG_SETTINGS = false;
285    static final boolean DEBUG_PREFERRED = false;
286    static final boolean DEBUG_UPGRADE = false;
287    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
288    private static final boolean DEBUG_BACKUP = false;
289    private static final boolean DEBUG_INSTALL = false;
290    private static final boolean DEBUG_REMOVE = false;
291    private static final boolean DEBUG_BROADCASTS = false;
292    private static final boolean DEBUG_SHOW_INFO = false;
293    private static final boolean DEBUG_PACKAGE_INFO = false;
294    private static final boolean DEBUG_INTENT_MATCHING = false;
295    private static final boolean DEBUG_PACKAGE_SCANNING = false;
296    private static final boolean DEBUG_VERIFY = false;
297    private static final boolean DEBUG_DEXOPT = false;
298    private static final boolean DEBUG_ABI_SELECTION = false;
299
300    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
301
302    private static final int RADIO_UID = Process.PHONE_UID;
303    private static final int LOG_UID = Process.LOG_UID;
304    private static final int NFC_UID = Process.NFC_UID;
305    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
306    private static final int SHELL_UID = Process.SHELL_UID;
307
308    // Cap the size of permission trees that 3rd party apps can define
309    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
310
311    // Suffix used during package installation when copying/moving
312    // package apks to install directory.
313    private static final String INSTALL_PACKAGE_SUFFIX = "-";
314
315    static final int SCAN_NO_DEX = 1<<1;
316    static final int SCAN_FORCE_DEX = 1<<2;
317    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
318    static final int SCAN_NEW_INSTALL = 1<<4;
319    static final int SCAN_NO_PATHS = 1<<5;
320    static final int SCAN_UPDATE_TIME = 1<<6;
321    static final int SCAN_DEFER_DEX = 1<<7;
322    static final int SCAN_BOOTING = 1<<8;
323    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
324    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
325    static final int SCAN_REQUIRE_KNOWN = 1<<12;
326    static final int SCAN_MOVE = 1<<13;
327    static final int SCAN_INITIAL = 1<<14;
328
329    static final int REMOVE_CHATTY = 1<<16;
330
331    private static final int[] EMPTY_INT_ARRAY = new int[0];
332
333    /**
334     * Timeout (in milliseconds) after which the watchdog should declare that
335     * our handler thread is wedged.  The usual default for such things is one
336     * minute but we sometimes do very lengthy I/O operations on this thread,
337     * such as installing multi-gigabyte applications, so ours needs to be longer.
338     */
339    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
340
341    /**
342     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
343     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
344     * settings entry if available, otherwise we use the hardcoded default.  If it's been
345     * more than this long since the last fstrim, we force one during the boot sequence.
346     *
347     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
348     * one gets run at the next available charging+idle time.  This final mandatory
349     * no-fstrim check kicks in only of the other scheduling criteria is never met.
350     */
351    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
352
353    /**
354     * Whether verification is enabled by default.
355     */
356    private static final boolean DEFAULT_VERIFY_ENABLE = true;
357
358    /**
359     * The default maximum time to wait for the verification agent to return in
360     * milliseconds.
361     */
362    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
363
364    /**
365     * The default response for package verification timeout.
366     *
367     * This can be either PackageManager.VERIFICATION_ALLOW or
368     * PackageManager.VERIFICATION_REJECT.
369     */
370    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
371
372    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
373
374    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
375            DEFAULT_CONTAINER_PACKAGE,
376            "com.android.defcontainer.DefaultContainerService");
377
378    private static final String KILL_APP_REASON_GIDS_CHANGED =
379            "permission grant or revoke changed gids";
380
381    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
382            "permissions revoked";
383
384    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
385
386    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
387
388    /** Permission grant: not grant the permission. */
389    private static final int GRANT_DENIED = 1;
390
391    /** Permission grant: grant the permission as an install permission. */
392    private static final int GRANT_INSTALL = 2;
393
394    /** Permission grant: grant the permission as an install permission for a legacy app. */
395    private static final int GRANT_INSTALL_LEGACY = 3;
396
397    /** Permission grant: grant the permission as a runtime one. */
398    private static final int GRANT_RUNTIME = 4;
399
400    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
401    private static final int GRANT_UPGRADE = 5;
402
403    /** Canonical intent used to identify what counts as a "web browser" app */
404    private static final Intent sBrowserIntent;
405    static {
406        sBrowserIntent = new Intent();
407        sBrowserIntent.setAction(Intent.ACTION_VIEW);
408        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
409        sBrowserIntent.setData(Uri.parse("http:"));
410    }
411
412    final ServiceThread mHandlerThread;
413
414    final PackageHandler mHandler;
415
416    /**
417     * Messages for {@link #mHandler} that need to wait for system ready before
418     * being dispatched.
419     */
420    private ArrayList<Message> mPostSystemReadyMessages;
421
422    final int mSdkVersion = Build.VERSION.SDK_INT;
423
424    final Context mContext;
425    final boolean mFactoryTest;
426    final boolean mOnlyCore;
427    final boolean mLazyDexOpt;
428    final long mDexOptLRUThresholdInMills;
429    final DisplayMetrics mMetrics;
430    final int mDefParseFlags;
431    final String[] mSeparateProcesses;
432    final boolean mIsUpgrade;
433
434    // This is where all application persistent data goes.
435    final File mAppDataDir;
436
437    // This is where all application persistent data goes for secondary users.
438    final File mUserAppDataDir;
439
440    /** The location for ASEC container files on internal storage. */
441    final String mAsecInternalPath;
442
443    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
444    // LOCK HELD.  Can be called with mInstallLock held.
445    @GuardedBy("mInstallLock")
446    final Installer mInstaller;
447
448    /** Directory where installed third-party apps stored */
449    final File mAppInstallDir;
450
451    /**
452     * Directory to which applications installed internally have their
453     * 32 bit native libraries copied.
454     */
455    private File mAppLib32InstallDir;
456
457    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
458    // apps.
459    final File mDrmAppPrivateInstallDir;
460
461    // ----------------------------------------------------------------
462
463    // Lock for state used when installing and doing other long running
464    // operations.  Methods that must be called with this lock held have
465    // the suffix "LI".
466    final Object mInstallLock = new Object();
467
468    // ----------------------------------------------------------------
469
470    // Keys are String (package name), values are Package.  This also serves
471    // as the lock for the global state.  Methods that must be called with
472    // this lock held have the prefix "LP".
473    @GuardedBy("mPackages")
474    final ArrayMap<String, PackageParser.Package> mPackages =
475            new ArrayMap<String, PackageParser.Package>();
476
477    // Tracks available target package names -> overlay package paths.
478    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
479        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
480
481    /**
482     * Tracks new system packages [receiving in an OTA] that we expect to
483     * find updated user-installed versions. Keys are package name, values
484     * are package location.
485     */
486    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
487
488    final Settings mSettings;
489    boolean mRestoredSettings;
490
491    // System configuration read by SystemConfig.
492    final int[] mGlobalGids;
493    final SparseArray<ArraySet<String>> mSystemPermissions;
494    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
495
496    // If mac_permissions.xml was found for seinfo labeling.
497    boolean mFoundPolicyFile;
498
499    // If a recursive restorecon of /data/data/<pkg> is needed.
500    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
501
502    public static final class SharedLibraryEntry {
503        public final String path;
504        public final String apk;
505
506        SharedLibraryEntry(String _path, String _apk) {
507            path = _path;
508            apk = _apk;
509        }
510    }
511
512    // Currently known shared libraries.
513    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
514            new ArrayMap<String, SharedLibraryEntry>();
515
516    // All available activities, for your resolving pleasure.
517    final ActivityIntentResolver mActivities =
518            new ActivityIntentResolver();
519
520    // All available receivers, for your resolving pleasure.
521    final ActivityIntentResolver mReceivers =
522            new ActivityIntentResolver();
523
524    // All available services, for your resolving pleasure.
525    final ServiceIntentResolver mServices = new ServiceIntentResolver();
526
527    // All available providers, for your resolving pleasure.
528    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
529
530    // Mapping from provider base names (first directory in content URI codePath)
531    // to the provider information.
532    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
533            new ArrayMap<String, PackageParser.Provider>();
534
535    // Mapping from instrumentation class names to info about them.
536    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
537            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
538
539    // Mapping from permission names to info about them.
540    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
541            new ArrayMap<String, PackageParser.PermissionGroup>();
542
543    // Packages whose data we have transfered into another package, thus
544    // should no longer exist.
545    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
546
547    // Broadcast actions that are only available to the system.
548    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
549
550    /** List of packages waiting for verification. */
551    final SparseArray<PackageVerificationState> mPendingVerification
552            = new SparseArray<PackageVerificationState>();
553
554    /** Set of packages associated with each app op permission. */
555    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
556
557    final PackageInstallerService mInstallerService;
558
559    private final PackageDexOptimizer mPackageDexOptimizer;
560
561    private AtomicInteger mNextMoveId = new AtomicInteger();
562    private final MoveCallbacks mMoveCallbacks;
563
564    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
565
566    // Cache of users who need badging.
567    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
568
569    /** Token for keys in mPendingVerification. */
570    private int mPendingVerificationToken = 0;
571
572    volatile boolean mSystemReady;
573    volatile boolean mSafeMode;
574    volatile boolean mHasSystemUidErrors;
575
576    ApplicationInfo mAndroidApplication;
577    final ActivityInfo mResolveActivity = new ActivityInfo();
578    final ResolveInfo mResolveInfo = new ResolveInfo();
579    ComponentName mResolveComponentName;
580    PackageParser.Package mPlatformPackage;
581    ComponentName mCustomResolverComponentName;
582
583    boolean mResolverReplaced = false;
584
585    private final ComponentName mIntentFilterVerifierComponent;
586    private int mIntentFilterVerificationToken = 0;
587
588    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
589            = new SparseArray<IntentFilterVerificationState>();
590
591    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
592            new DefaultPermissionGrantPolicy(this);
593
594    private static class IFVerificationParams {
595        PackageParser.Package pkg;
596        boolean replacing;
597        int userId;
598        int verifierUid;
599
600        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
601                int _userId, int _verifierUid) {
602            pkg = _pkg;
603            replacing = _replacing;
604            userId = _userId;
605            replacing = _replacing;
606            verifierUid = _verifierUid;
607        }
608    }
609
610    private interface IntentFilterVerifier<T extends IntentFilter> {
611        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
612                                               T filter, String packageName);
613        void startVerifications(int userId);
614        void receiveVerificationResponse(int verificationId);
615    }
616
617    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
618        private Context mContext;
619        private ComponentName mIntentFilterVerifierComponent;
620        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
621
622        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
623            mContext = context;
624            mIntentFilterVerifierComponent = verifierComponent;
625        }
626
627        private String getDefaultScheme() {
628            return IntentFilter.SCHEME_HTTPS;
629        }
630
631        @Override
632        public void startVerifications(int userId) {
633            // Launch verifications requests
634            int count = mCurrentIntentFilterVerifications.size();
635            for (int n=0; n<count; n++) {
636                int verificationId = mCurrentIntentFilterVerifications.get(n);
637                final IntentFilterVerificationState ivs =
638                        mIntentFilterVerificationStates.get(verificationId);
639
640                String packageName = ivs.getPackageName();
641
642                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
643                final int filterCount = filters.size();
644                ArraySet<String> domainsSet = new ArraySet<>();
645                for (int m=0; m<filterCount; m++) {
646                    PackageParser.ActivityIntentInfo filter = filters.get(m);
647                    domainsSet.addAll(filter.getHostsList());
648                }
649                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
650                synchronized (mPackages) {
651                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
652                            packageName, domainsList) != null) {
653                        scheduleWriteSettingsLocked();
654                    }
655                }
656                sendVerificationRequest(userId, verificationId, ivs);
657            }
658            mCurrentIntentFilterVerifications.clear();
659        }
660
661        private void sendVerificationRequest(int userId, int verificationId,
662                IntentFilterVerificationState ivs) {
663
664            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
665            verificationIntent.putExtra(
666                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
667                    verificationId);
668            verificationIntent.putExtra(
669                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
670                    getDefaultScheme());
671            verificationIntent.putExtra(
672                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
673                    ivs.getHostsString());
674            verificationIntent.putExtra(
675                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
676                    ivs.getPackageName());
677            verificationIntent.setComponent(mIntentFilterVerifierComponent);
678            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
679
680            UserHandle user = new UserHandle(userId);
681            mContext.sendBroadcastAsUser(verificationIntent, user);
682            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
683                    "Sending IntentFilter verification broadcast");
684        }
685
686        public void receiveVerificationResponse(int verificationId) {
687            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
688
689            final boolean verified = ivs.isVerified();
690
691            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
692            final int count = filters.size();
693            if (DEBUG_DOMAIN_VERIFICATION) {
694                Slog.i(TAG, "Received verification response " + verificationId
695                        + " for " + count + " filters, verified=" + verified);
696            }
697            for (int n=0; n<count; n++) {
698                PackageParser.ActivityIntentInfo filter = filters.get(n);
699                filter.setVerified(verified);
700
701                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
702                        + " verified with result:" + verified + " and hosts:"
703                        + ivs.getHostsString());
704            }
705
706            mIntentFilterVerificationStates.remove(verificationId);
707
708            final String packageName = ivs.getPackageName();
709            IntentFilterVerificationInfo ivi = null;
710
711            synchronized (mPackages) {
712                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
713            }
714            if (ivi == null) {
715                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
716                        + verificationId + " packageName:" + packageName);
717                return;
718            }
719            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
720                    "Updating IntentFilterVerificationInfo for package " + packageName
721                            +" verificationId:" + verificationId);
722
723            synchronized (mPackages) {
724                if (verified) {
725                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
726                } else {
727                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
728                }
729                scheduleWriteSettingsLocked();
730
731                final int userId = ivs.getUserId();
732                if (userId != UserHandle.USER_ALL) {
733                    final int userStatus =
734                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
735
736                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
737                    boolean needUpdate = false;
738
739                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
740                    // already been set by the User thru the Disambiguation dialog
741                    switch (userStatus) {
742                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
743                            if (verified) {
744                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
745                            } else {
746                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
747                            }
748                            needUpdate = true;
749                            break;
750
751                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
752                            if (verified) {
753                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
754                                needUpdate = true;
755                            }
756                            break;
757
758                        default:
759                            // Nothing to do
760                    }
761
762                    if (needUpdate) {
763                        mSettings.updateIntentFilterVerificationStatusLPw(
764                                packageName, updatedStatus, userId);
765                        scheduleWritePackageRestrictionsLocked(userId);
766                    }
767                }
768            }
769        }
770
771        @Override
772        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
773                    ActivityIntentInfo filter, String packageName) {
774            if (!hasValidDomains(filter)) {
775                return false;
776            }
777            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
778            if (ivs == null) {
779                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
780                        packageName);
781            }
782            if (DEBUG_DOMAIN_VERIFICATION) {
783                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
784            }
785            ivs.addFilter(filter);
786            return true;
787        }
788
789        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
790                int userId, int verificationId, String packageName) {
791            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
792                    verifierUid, userId, packageName);
793            ivs.setPendingState();
794            synchronized (mPackages) {
795                mIntentFilterVerificationStates.append(verificationId, ivs);
796                mCurrentIntentFilterVerifications.add(verificationId);
797            }
798            return ivs;
799        }
800    }
801
802    private static boolean hasValidDomains(ActivityIntentInfo filter) {
803        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
804                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
805        if (!hasHTTPorHTTPS) {
806            return false;
807        }
808        return true;
809    }
810
811    private IntentFilterVerifier mIntentFilterVerifier;
812
813    // Set of pending broadcasts for aggregating enable/disable of components.
814    static class PendingPackageBroadcasts {
815        // for each user id, a map of <package name -> components within that package>
816        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
817
818        public PendingPackageBroadcasts() {
819            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
820        }
821
822        public ArrayList<String> get(int userId, String packageName) {
823            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
824            return packages.get(packageName);
825        }
826
827        public void put(int userId, String packageName, ArrayList<String> components) {
828            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
829            packages.put(packageName, components);
830        }
831
832        public void remove(int userId, String packageName) {
833            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
834            if (packages != null) {
835                packages.remove(packageName);
836            }
837        }
838
839        public void remove(int userId) {
840            mUidMap.remove(userId);
841        }
842
843        public int userIdCount() {
844            return mUidMap.size();
845        }
846
847        public int userIdAt(int n) {
848            return mUidMap.keyAt(n);
849        }
850
851        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
852            return mUidMap.get(userId);
853        }
854
855        public int size() {
856            // total number of pending broadcast entries across all userIds
857            int num = 0;
858            for (int i = 0; i< mUidMap.size(); i++) {
859                num += mUidMap.valueAt(i).size();
860            }
861            return num;
862        }
863
864        public void clear() {
865            mUidMap.clear();
866        }
867
868        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
869            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
870            if (map == null) {
871                map = new ArrayMap<String, ArrayList<String>>();
872                mUidMap.put(userId, map);
873            }
874            return map;
875        }
876    }
877    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
878
879    // Service Connection to remote media container service to copy
880    // package uri's from external media onto secure containers
881    // or internal storage.
882    private IMediaContainerService mContainerService = null;
883
884    static final int SEND_PENDING_BROADCAST = 1;
885    static final int MCS_BOUND = 3;
886    static final int END_COPY = 4;
887    static final int INIT_COPY = 5;
888    static final int MCS_UNBIND = 6;
889    static final int START_CLEANING_PACKAGE = 7;
890    static final int FIND_INSTALL_LOC = 8;
891    static final int POST_INSTALL = 9;
892    static final int MCS_RECONNECT = 10;
893    static final int MCS_GIVE_UP = 11;
894    static final int UPDATED_MEDIA_STATUS = 12;
895    static final int WRITE_SETTINGS = 13;
896    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
897    static final int PACKAGE_VERIFIED = 15;
898    static final int CHECK_PENDING_VERIFICATION = 16;
899    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
900    static final int INTENT_FILTER_VERIFIED = 18;
901
902    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
903
904    // Delay time in millisecs
905    static final int BROADCAST_DELAY = 10 * 1000;
906
907    static UserManagerService sUserManager;
908
909    // Stores a list of users whose package restrictions file needs to be updated
910    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
911
912    final private DefaultContainerConnection mDefContainerConn =
913            new DefaultContainerConnection();
914    class DefaultContainerConnection implements ServiceConnection {
915        public void onServiceConnected(ComponentName name, IBinder service) {
916            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
917            IMediaContainerService imcs =
918                IMediaContainerService.Stub.asInterface(service);
919            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
920        }
921
922        public void onServiceDisconnected(ComponentName name) {
923            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
924        }
925    }
926
927    // Recordkeeping of restore-after-install operations that are currently in flight
928    // between the Package Manager and the Backup Manager
929    class PostInstallData {
930        public InstallArgs args;
931        public PackageInstalledInfo res;
932
933        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
934            args = _a;
935            res = _r;
936        }
937    }
938
939    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
940    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
941
942    // XML tags for backup/restore of various bits of state
943    private static final String TAG_PREFERRED_BACKUP = "pa";
944    private static final String TAG_DEFAULT_APPS = "da";
945    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
946
947    final String mRequiredVerifierPackage;
948    final String mRequiredInstallerPackage;
949
950    private final PackageUsage mPackageUsage = new PackageUsage();
951
952    private class PackageUsage {
953        private static final int WRITE_INTERVAL
954            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
955
956        private final Object mFileLock = new Object();
957        private final AtomicLong mLastWritten = new AtomicLong(0);
958        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
959
960        private boolean mIsHistoricalPackageUsageAvailable = true;
961
962        boolean isHistoricalPackageUsageAvailable() {
963            return mIsHistoricalPackageUsageAvailable;
964        }
965
966        void write(boolean force) {
967            if (force) {
968                writeInternal();
969                return;
970            }
971            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
972                && !DEBUG_DEXOPT) {
973                return;
974            }
975            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
976                new Thread("PackageUsage_DiskWriter") {
977                    @Override
978                    public void run() {
979                        try {
980                            writeInternal();
981                        } finally {
982                            mBackgroundWriteRunning.set(false);
983                        }
984                    }
985                }.start();
986            }
987        }
988
989        private void writeInternal() {
990            synchronized (mPackages) {
991                synchronized (mFileLock) {
992                    AtomicFile file = getFile();
993                    FileOutputStream f = null;
994                    try {
995                        f = file.startWrite();
996                        BufferedOutputStream out = new BufferedOutputStream(f);
997                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
998                        StringBuilder sb = new StringBuilder();
999                        for (PackageParser.Package pkg : mPackages.values()) {
1000                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1001                                continue;
1002                            }
1003                            sb.setLength(0);
1004                            sb.append(pkg.packageName);
1005                            sb.append(' ');
1006                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1007                            sb.append('\n');
1008                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1009                        }
1010                        out.flush();
1011                        file.finishWrite(f);
1012                    } catch (IOException e) {
1013                        if (f != null) {
1014                            file.failWrite(f);
1015                        }
1016                        Log.e(TAG, "Failed to write package usage times", e);
1017                    }
1018                }
1019            }
1020            mLastWritten.set(SystemClock.elapsedRealtime());
1021        }
1022
1023        void readLP() {
1024            synchronized (mFileLock) {
1025                AtomicFile file = getFile();
1026                BufferedInputStream in = null;
1027                try {
1028                    in = new BufferedInputStream(file.openRead());
1029                    StringBuffer sb = new StringBuffer();
1030                    while (true) {
1031                        String packageName = readToken(in, sb, ' ');
1032                        if (packageName == null) {
1033                            break;
1034                        }
1035                        String timeInMillisString = readToken(in, sb, '\n');
1036                        if (timeInMillisString == null) {
1037                            throw new IOException("Failed to find last usage time for package "
1038                                                  + packageName);
1039                        }
1040                        PackageParser.Package pkg = mPackages.get(packageName);
1041                        if (pkg == null) {
1042                            continue;
1043                        }
1044                        long timeInMillis;
1045                        try {
1046                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1047                        } catch (NumberFormatException e) {
1048                            throw new IOException("Failed to parse " + timeInMillisString
1049                                                  + " as a long.", e);
1050                        }
1051                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1052                    }
1053                } catch (FileNotFoundException expected) {
1054                    mIsHistoricalPackageUsageAvailable = false;
1055                } catch (IOException e) {
1056                    Log.w(TAG, "Failed to read package usage times", e);
1057                } finally {
1058                    IoUtils.closeQuietly(in);
1059                }
1060            }
1061            mLastWritten.set(SystemClock.elapsedRealtime());
1062        }
1063
1064        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1065                throws IOException {
1066            sb.setLength(0);
1067            while (true) {
1068                int ch = in.read();
1069                if (ch == -1) {
1070                    if (sb.length() == 0) {
1071                        return null;
1072                    }
1073                    throw new IOException("Unexpected EOF");
1074                }
1075                if (ch == endOfToken) {
1076                    return sb.toString();
1077                }
1078                sb.append((char)ch);
1079            }
1080        }
1081
1082        private AtomicFile getFile() {
1083            File dataDir = Environment.getDataDirectory();
1084            File systemDir = new File(dataDir, "system");
1085            File fname = new File(systemDir, "package-usage.list");
1086            return new AtomicFile(fname);
1087        }
1088    }
1089
1090    class PackageHandler extends Handler {
1091        private boolean mBound = false;
1092        final ArrayList<HandlerParams> mPendingInstalls =
1093            new ArrayList<HandlerParams>();
1094
1095        private boolean connectToService() {
1096            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1097                    " DefaultContainerService");
1098            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1099            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1100            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1101                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1102                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1103                mBound = true;
1104                return true;
1105            }
1106            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1107            return false;
1108        }
1109
1110        private void disconnectService() {
1111            mContainerService = null;
1112            mBound = false;
1113            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1114            mContext.unbindService(mDefContainerConn);
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116        }
1117
1118        PackageHandler(Looper looper) {
1119            super(looper);
1120        }
1121
1122        public void handleMessage(Message msg) {
1123            try {
1124                doHandleMessage(msg);
1125            } finally {
1126                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127            }
1128        }
1129
1130        void doHandleMessage(Message msg) {
1131            switch (msg.what) {
1132                case INIT_COPY: {
1133                    HandlerParams params = (HandlerParams) msg.obj;
1134                    int idx = mPendingInstalls.size();
1135                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1136                    // If a bind was already initiated we dont really
1137                    // need to do anything. The pending install
1138                    // will be processed later on.
1139                    if (!mBound) {
1140                        // If this is the only one pending we might
1141                        // have to bind to the service again.
1142                        if (!connectToService()) {
1143                            Slog.e(TAG, "Failed to bind to media container service");
1144                            params.serviceError();
1145                            return;
1146                        } else {
1147                            // Once we bind to the service, the first
1148                            // pending request will be processed.
1149                            mPendingInstalls.add(idx, params);
1150                        }
1151                    } else {
1152                        mPendingInstalls.add(idx, params);
1153                        // Already bound to the service. Just make
1154                        // sure we trigger off processing the first request.
1155                        if (idx == 0) {
1156                            mHandler.sendEmptyMessage(MCS_BOUND);
1157                        }
1158                    }
1159                    break;
1160                }
1161                case MCS_BOUND: {
1162                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1163                    if (msg.obj != null) {
1164                        mContainerService = (IMediaContainerService) msg.obj;
1165                    }
1166                    if (mContainerService == null) {
1167                        if (!mBound) {
1168                            // Something seriously wrong since we are not bound and we are not
1169                            // waiting for connection. Bail out.
1170                            Slog.e(TAG, "Cannot bind to media container service");
1171                            for (HandlerParams params : mPendingInstalls) {
1172                                // Indicate service bind error
1173                                params.serviceError();
1174                            }
1175                            mPendingInstalls.clear();
1176                        } else {
1177                            Slog.w(TAG, "Waiting to connect to media container service");
1178                        }
1179                    } else if (mPendingInstalls.size() > 0) {
1180                        HandlerParams params = mPendingInstalls.get(0);
1181                        if (params != null) {
1182                            if (params.startCopy()) {
1183                                // We are done...  look for more work or to
1184                                // go idle.
1185                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1186                                        "Checking for more work or unbind...");
1187                                // Delete pending install
1188                                if (mPendingInstalls.size() > 0) {
1189                                    mPendingInstalls.remove(0);
1190                                }
1191                                if (mPendingInstalls.size() == 0) {
1192                                    if (mBound) {
1193                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1194                                                "Posting delayed MCS_UNBIND");
1195                                        removeMessages(MCS_UNBIND);
1196                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1197                                        // Unbind after a little delay, to avoid
1198                                        // continual thrashing.
1199                                        sendMessageDelayed(ubmsg, 10000);
1200                                    }
1201                                } else {
1202                                    // There are more pending requests in queue.
1203                                    // Just post MCS_BOUND message to trigger processing
1204                                    // of next pending install.
1205                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1206                                            "Posting MCS_BOUND for next work");
1207                                    mHandler.sendEmptyMessage(MCS_BOUND);
1208                                }
1209                            }
1210                        }
1211                    } else {
1212                        // Should never happen ideally.
1213                        Slog.w(TAG, "Empty queue");
1214                    }
1215                    break;
1216                }
1217                case MCS_RECONNECT: {
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1219                    if (mPendingInstalls.size() > 0) {
1220                        if (mBound) {
1221                            disconnectService();
1222                        }
1223                        if (!connectToService()) {
1224                            Slog.e(TAG, "Failed to bind to media container service");
1225                            for (HandlerParams params : mPendingInstalls) {
1226                                // Indicate service bind error
1227                                params.serviceError();
1228                            }
1229                            mPendingInstalls.clear();
1230                        }
1231                    }
1232                    break;
1233                }
1234                case MCS_UNBIND: {
1235                    // If there is no actual work left, then time to unbind.
1236                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1237
1238                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1239                        if (mBound) {
1240                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1241
1242                            disconnectService();
1243                        }
1244                    } else if (mPendingInstalls.size() > 0) {
1245                        // There are more pending requests in queue.
1246                        // Just post MCS_BOUND message to trigger processing
1247                        // of next pending install.
1248                        mHandler.sendEmptyMessage(MCS_BOUND);
1249                    }
1250
1251                    break;
1252                }
1253                case MCS_GIVE_UP: {
1254                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1255                    mPendingInstalls.remove(0);
1256                    break;
1257                }
1258                case SEND_PENDING_BROADCAST: {
1259                    String packages[];
1260                    ArrayList<String> components[];
1261                    int size = 0;
1262                    int uids[];
1263                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1264                    synchronized (mPackages) {
1265                        if (mPendingBroadcasts == null) {
1266                            return;
1267                        }
1268                        size = mPendingBroadcasts.size();
1269                        if (size <= 0) {
1270                            // Nothing to be done. Just return
1271                            return;
1272                        }
1273                        packages = new String[size];
1274                        components = new ArrayList[size];
1275                        uids = new int[size];
1276                        int i = 0;  // filling out the above arrays
1277
1278                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1279                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1280                            Iterator<Map.Entry<String, ArrayList<String>>> it
1281                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1282                                            .entrySet().iterator();
1283                            while (it.hasNext() && i < size) {
1284                                Map.Entry<String, ArrayList<String>> ent = it.next();
1285                                packages[i] = ent.getKey();
1286                                components[i] = ent.getValue();
1287                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1288                                uids[i] = (ps != null)
1289                                        ? UserHandle.getUid(packageUserId, ps.appId)
1290                                        : -1;
1291                                i++;
1292                            }
1293                        }
1294                        size = i;
1295                        mPendingBroadcasts.clear();
1296                    }
1297                    // Send broadcasts
1298                    for (int i = 0; i < size; i++) {
1299                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1300                    }
1301                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1302                    break;
1303                }
1304                case START_CLEANING_PACKAGE: {
1305                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1306                    final String packageName = (String)msg.obj;
1307                    final int userId = msg.arg1;
1308                    final boolean andCode = msg.arg2 != 0;
1309                    synchronized (mPackages) {
1310                        if (userId == UserHandle.USER_ALL) {
1311                            int[] users = sUserManager.getUserIds();
1312                            for (int user : users) {
1313                                mSettings.addPackageToCleanLPw(
1314                                        new PackageCleanItem(user, packageName, andCode));
1315                            }
1316                        } else {
1317                            mSettings.addPackageToCleanLPw(
1318                                    new PackageCleanItem(userId, packageName, andCode));
1319                        }
1320                    }
1321                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1322                    startCleaningPackages();
1323                } break;
1324                case POST_INSTALL: {
1325                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1326                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1327                    mRunningInstalls.delete(msg.arg1);
1328                    boolean deleteOld = false;
1329
1330                    if (data != null) {
1331                        InstallArgs args = data.args;
1332                        PackageInstalledInfo res = data.res;
1333
1334                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1335                            final String packageName = res.pkg.applicationInfo.packageName;
1336                            res.removedInfo.sendBroadcast(false, true, false);
1337                            Bundle extras = new Bundle(1);
1338                            extras.putInt(Intent.EXTRA_UID, res.uid);
1339
1340                            // Now that we successfully installed the package, grant runtime
1341                            // permissions if requested before broadcasting the install.
1342                            if ((args.installFlags
1343                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1344                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1345                                        args.installGrantPermissions);
1346                            }
1347
1348                            // Determine the set of users who are adding this
1349                            // package for the first time vs. those who are seeing
1350                            // an update.
1351                            int[] firstUsers;
1352                            int[] updateUsers = new int[0];
1353                            if (res.origUsers == null || res.origUsers.length == 0) {
1354                                firstUsers = res.newUsers;
1355                            } else {
1356                                firstUsers = new int[0];
1357                                for (int i=0; i<res.newUsers.length; i++) {
1358                                    int user = res.newUsers[i];
1359                                    boolean isNew = true;
1360                                    for (int j=0; j<res.origUsers.length; j++) {
1361                                        if (res.origUsers[j] == user) {
1362                                            isNew = false;
1363                                            break;
1364                                        }
1365                                    }
1366                                    if (isNew) {
1367                                        int[] newFirst = new int[firstUsers.length+1];
1368                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1369                                                firstUsers.length);
1370                                        newFirst[firstUsers.length] = user;
1371                                        firstUsers = newFirst;
1372                                    } else {
1373                                        int[] newUpdate = new int[updateUsers.length+1];
1374                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1375                                                updateUsers.length);
1376                                        newUpdate[updateUsers.length] = user;
1377                                        updateUsers = newUpdate;
1378                                    }
1379                                }
1380                            }
1381                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1382                                    packageName, extras, null, null, firstUsers);
1383                            final boolean update = res.removedInfo.removedPackage != null;
1384                            if (update) {
1385                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1386                            }
1387                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1388                                    packageName, extras, null, null, updateUsers);
1389                            if (update) {
1390                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1391                                        packageName, extras, null, null, updateUsers);
1392                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1393                                        null, null, packageName, null, updateUsers);
1394
1395                                // treat asec-hosted packages like removable media on upgrade
1396                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1397                                    if (DEBUG_INSTALL) {
1398                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1399                                                + " is ASEC-hosted -> AVAILABLE");
1400                                    }
1401                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1402                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1403                                    pkgList.add(packageName);
1404                                    sendResourcesChangedBroadcast(true, true,
1405                                            pkgList,uidArray, null);
1406                                }
1407                            }
1408                            if (res.removedInfo.args != null) {
1409                                // Remove the replaced package's older resources safely now
1410                                deleteOld = true;
1411                            }
1412
1413                            // If this app is a browser and it's newly-installed for some
1414                            // users, clear any default-browser state in those users
1415                            if (firstUsers.length > 0) {
1416                                // the app's nature doesn't depend on the user, so we can just
1417                                // check its browser nature in any user and generalize.
1418                                if (packageIsBrowser(packageName, firstUsers[0])) {
1419                                    synchronized (mPackages) {
1420                                        for (int userId : firstUsers) {
1421                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1422                                        }
1423                                    }
1424                                }
1425                            }
1426                            // Log current value of "unknown sources" setting
1427                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1428                                getUnknownSourcesSettings());
1429                        }
1430                        // Force a gc to clear up things
1431                        Runtime.getRuntime().gc();
1432                        // We delete after a gc for applications  on sdcard.
1433                        if (deleteOld) {
1434                            synchronized (mInstallLock) {
1435                                res.removedInfo.args.doPostDeleteLI(true);
1436                            }
1437                        }
1438                        if (args.observer != null) {
1439                            try {
1440                                Bundle extras = extrasForInstallResult(res);
1441                                args.observer.onPackageInstalled(res.name, res.returnCode,
1442                                        res.returnMsg, extras);
1443                            } catch (RemoteException e) {
1444                                Slog.i(TAG, "Observer no longer exists.");
1445                            }
1446                        }
1447                    } else {
1448                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1449                    }
1450                } break;
1451                case UPDATED_MEDIA_STATUS: {
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453                    boolean reportStatus = msg.arg1 == 1;
1454                    boolean doGc = msg.arg2 == 1;
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456                    if (doGc) {
1457                        // Force a gc to clear up stale containers.
1458                        Runtime.getRuntime().gc();
1459                    }
1460                    if (msg.obj != null) {
1461                        @SuppressWarnings("unchecked")
1462                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464                        // Unload containers
1465                        unloadAllContainers(args);
1466                    }
1467                    if (reportStatus) {
1468                        try {
1469                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470                            PackageHelper.getMountService().finishMediaUpdate();
1471                        } catch (RemoteException e) {
1472                            Log.e(TAG, "MountService not running?");
1473                        }
1474                    }
1475                } break;
1476                case WRITE_SETTINGS: {
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                    synchronized (mPackages) {
1479                        removeMessages(WRITE_SETTINGS);
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        mSettings.writeLPr();
1482                        mDirtyUsers.clear();
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case WRITE_PACKAGE_RESTRICTIONS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        for (int userId : mDirtyUsers) {
1491                            mSettings.writePackageRestrictionsLPr(userId);
1492                        }
1493                        mDirtyUsers.clear();
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                } break;
1497                case CHECK_PENDING_VERIFICATION: {
1498                    final int verificationId = msg.arg1;
1499                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1500
1501                    if ((state != null) && !state.timeoutExtended()) {
1502                        final InstallArgs args = state.getInstallArgs();
1503                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1504
1505                        Slog.i(TAG, "Verification timed out for " + originUri);
1506                        mPendingVerification.remove(verificationId);
1507
1508                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1509
1510                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1511                            Slog.i(TAG, "Continuing with installation of " + originUri);
1512                            state.setVerifierResponse(Binder.getCallingUid(),
1513                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1514                            broadcastPackageVerified(verificationId, originUri,
1515                                    PackageManager.VERIFICATION_ALLOW,
1516                                    state.getInstallArgs().getUser());
1517                            try {
1518                                ret = args.copyApk(mContainerService, true);
1519                            } catch (RemoteException e) {
1520                                Slog.e(TAG, "Could not contact the ContainerService");
1521                            }
1522                        } else {
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_REJECT,
1525                                    state.getInstallArgs().getUser());
1526                        }
1527
1528                        processPendingInstall(args, ret);
1529                        mHandler.sendEmptyMessage(MCS_UNBIND);
1530                    }
1531                    break;
1532                }
1533                case PACKAGE_VERIFIED: {
1534                    final int verificationId = msg.arg1;
1535
1536                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1537                    if (state == null) {
1538                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1539                        break;
1540                    }
1541
1542                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1543
1544                    state.setVerifierResponse(response.callerUid, response.code);
1545
1546                    if (state.isVerificationComplete()) {
1547                        mPendingVerification.remove(verificationId);
1548
1549                        final InstallArgs args = state.getInstallArgs();
1550                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1551
1552                        int ret;
1553                        if (state.isInstallAllowed()) {
1554                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1555                            broadcastPackageVerified(verificationId, originUri,
1556                                    response.code, state.getInstallArgs().getUser());
1557                            try {
1558                                ret = args.copyApk(mContainerService, true);
1559                            } catch (RemoteException e) {
1560                                Slog.e(TAG, "Could not contact the ContainerService");
1561                            }
1562                        } else {
1563                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1564                        }
1565
1566                        processPendingInstall(args, ret);
1567
1568                        mHandler.sendEmptyMessage(MCS_UNBIND);
1569                    }
1570
1571                    break;
1572                }
1573                case START_INTENT_FILTER_VERIFICATIONS: {
1574                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1575                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1576                            params.replacing, params.pkg);
1577                    break;
1578                }
1579                case INTENT_FILTER_VERIFIED: {
1580                    final int verificationId = msg.arg1;
1581
1582                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1583                            verificationId);
1584                    if (state == null) {
1585                        Slog.w(TAG, "Invalid IntentFilter verification token "
1586                                + verificationId + " received");
1587                        break;
1588                    }
1589
1590                    final int userId = state.getUserId();
1591
1592                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1593                            "Processing IntentFilter verification with token:"
1594                            + verificationId + " and userId:" + userId);
1595
1596                    final IntentFilterVerificationResponse response =
1597                            (IntentFilterVerificationResponse) msg.obj;
1598
1599                    state.setVerifierResponse(response.callerUid, response.code);
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "IntentFilter verification with token:" + verificationId
1603                            + " and userId:" + userId
1604                            + " is settings verifier response with response code:"
1605                            + response.code);
1606
1607                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1608                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1609                                + response.getFailedDomainsString());
1610                    }
1611
1612                    if (state.isVerificationComplete()) {
1613                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1614                    } else {
1615                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1616                                "IntentFilter verification with token:" + verificationId
1617                                + " was not said to be complete");
1618                    }
1619
1620                    break;
1621                }
1622            }
1623        }
1624    }
1625
1626    private StorageEventListener mStorageListener = new StorageEventListener() {
1627        @Override
1628        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1629            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1630                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1631                    final String volumeUuid = vol.getFsUuid();
1632
1633                    // Clean up any users or apps that were removed or recreated
1634                    // while this volume was missing
1635                    reconcileUsers(volumeUuid);
1636                    reconcileApps(volumeUuid);
1637
1638                    // Clean up any install sessions that expired or were
1639                    // cancelled while this volume was missing
1640                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1641
1642                    loadPrivatePackages(vol);
1643
1644                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1645                    unloadPrivatePackages(vol);
1646                }
1647            }
1648
1649            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1650                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1651                    updateExternalMediaStatus(true, false);
1652                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1653                    updateExternalMediaStatus(false, false);
1654                }
1655            }
1656        }
1657
1658        @Override
1659        public void onVolumeForgotten(String fsUuid) {
1660            // Remove any apps installed on the forgotten volume
1661            synchronized (mPackages) {
1662                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1663                for (PackageSetting ps : packages) {
1664                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1665                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1666                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1667                }
1668
1669                mSettings.writeLPr();
1670            }
1671        }
1672    };
1673
1674    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1675            String[] grantedPermissions) {
1676        if (userId >= UserHandle.USER_OWNER) {
1677            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1678        } else if (userId == UserHandle.USER_ALL) {
1679            final int[] userIds;
1680            synchronized (mPackages) {
1681                userIds = UserManagerService.getInstance().getUserIds();
1682            }
1683            for (int someUserId : userIds) {
1684                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1685            }
1686        }
1687
1688        // We could have touched GID membership, so flush out packages.list
1689        synchronized (mPackages) {
1690            mSettings.writePackageListLPr();
1691        }
1692    }
1693
1694    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1695            String[] grantedPermissions) {
1696        SettingBase sb = (SettingBase) pkg.mExtras;
1697        if (sb == null) {
1698            return;
1699        }
1700
1701        PermissionsState permissionsState = sb.getPermissionsState();
1702
1703        for (String permission : pkg.requestedPermissions) {
1704            BasePermission bp = mSettings.mPermissions.get(permission);
1705            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1706                    || ArrayUtils.contains(grantedPermissions, permission))) {
1707                permissionsState.grantRuntimePermission(bp, userId);
1708            }
1709        }
1710    }
1711
1712    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1713        Bundle extras = null;
1714        switch (res.returnCode) {
1715            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1716                extras = new Bundle();
1717                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1718                        res.origPermission);
1719                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1720                        res.origPackage);
1721                break;
1722            }
1723            case PackageManager.INSTALL_SUCCEEDED: {
1724                extras = new Bundle();
1725                extras.putBoolean(Intent.EXTRA_REPLACING,
1726                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1727                break;
1728            }
1729        }
1730        return extras;
1731    }
1732
1733    void scheduleWriteSettingsLocked() {
1734        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1735            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1736        }
1737    }
1738
1739    void scheduleWritePackageRestrictionsLocked(int userId) {
1740        if (!sUserManager.exists(userId)) return;
1741        mDirtyUsers.add(userId);
1742        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1743            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1744        }
1745    }
1746
1747    public static PackageManagerService main(Context context, Installer installer,
1748            boolean factoryTest, boolean onlyCore) {
1749        PackageManagerService m = new PackageManagerService(context, installer,
1750                factoryTest, onlyCore);
1751        ServiceManager.addService("package", m);
1752        return m;
1753    }
1754
1755    static String[] splitString(String str, char sep) {
1756        int count = 1;
1757        int i = 0;
1758        while ((i=str.indexOf(sep, i)) >= 0) {
1759            count++;
1760            i++;
1761        }
1762
1763        String[] res = new String[count];
1764        i=0;
1765        count = 0;
1766        int lastI=0;
1767        while ((i=str.indexOf(sep, i)) >= 0) {
1768            res[count] = str.substring(lastI, i);
1769            count++;
1770            i++;
1771            lastI = i;
1772        }
1773        res[count] = str.substring(lastI, str.length());
1774        return res;
1775    }
1776
1777    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1778        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1779                Context.DISPLAY_SERVICE);
1780        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1781    }
1782
1783    public PackageManagerService(Context context, Installer installer,
1784            boolean factoryTest, boolean onlyCore) {
1785        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1786                SystemClock.uptimeMillis());
1787
1788        if (mSdkVersion <= 0) {
1789            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1790        }
1791
1792        mContext = context;
1793        mFactoryTest = factoryTest;
1794        mOnlyCore = onlyCore;
1795        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1796        mMetrics = new DisplayMetrics();
1797        mSettings = new Settings(mPackages);
1798        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810
1811        // TODO: add a property to control this?
1812        long dexOptLRUThresholdInMinutes;
1813        if (mLazyDexOpt) {
1814            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1815        } else {
1816            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1817        }
1818        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1819
1820        String separateProcesses = SystemProperties.get("debug.separate_processes");
1821        if (separateProcesses != null && separateProcesses.length() > 0) {
1822            if ("*".equals(separateProcesses)) {
1823                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1824                mSeparateProcesses = null;
1825                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1826            } else {
1827                mDefParseFlags = 0;
1828                mSeparateProcesses = separateProcesses.split(",");
1829                Slog.w(TAG, "Running with debug.separate_processes: "
1830                        + separateProcesses);
1831            }
1832        } else {
1833            mDefParseFlags = 0;
1834            mSeparateProcesses = null;
1835        }
1836
1837        mInstaller = installer;
1838        mPackageDexOptimizer = new PackageDexOptimizer(this);
1839        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1840
1841        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1842                FgThread.get().getLooper());
1843
1844        getDefaultDisplayMetrics(context, mMetrics);
1845
1846        SystemConfig systemConfig = SystemConfig.getInstance();
1847        mGlobalGids = systemConfig.getGlobalGids();
1848        mSystemPermissions = systemConfig.getSystemPermissions();
1849        mAvailableFeatures = systemConfig.getAvailableFeatures();
1850
1851        synchronized (mInstallLock) {
1852        // writer
1853        synchronized (mPackages) {
1854            mHandlerThread = new ServiceThread(TAG,
1855                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1856            mHandlerThread.start();
1857            mHandler = new PackageHandler(mHandlerThread.getLooper());
1858            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1859
1860            File dataDir = Environment.getDataDirectory();
1861            mAppDataDir = new File(dataDir, "data");
1862            mAppInstallDir = new File(dataDir, "app");
1863            mAppLib32InstallDir = new File(dataDir, "app-lib");
1864            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1865            mUserAppDataDir = new File(dataDir, "user");
1866            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1867
1868            sUserManager = new UserManagerService(context, this,
1869                    mInstallLock, mPackages);
1870
1871            // Propagate permission configuration in to package manager.
1872            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1873                    = systemConfig.getPermissions();
1874            for (int i=0; i<permConfig.size(); i++) {
1875                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1876                BasePermission bp = mSettings.mPermissions.get(perm.name);
1877                if (bp == null) {
1878                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1879                    mSettings.mPermissions.put(perm.name, bp);
1880                }
1881                if (perm.gids != null) {
1882                    bp.setGids(perm.gids, perm.perUser);
1883                }
1884            }
1885
1886            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1887            for (int i=0; i<libConfig.size(); i++) {
1888                mSharedLibraries.put(libConfig.keyAt(i),
1889                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1890            }
1891
1892            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1893
1894            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1895                    mSdkVersion, mOnlyCore);
1896
1897            String customResolverActivity = Resources.getSystem().getString(
1898                    R.string.config_customResolverActivity);
1899            if (TextUtils.isEmpty(customResolverActivity)) {
1900                customResolverActivity = null;
1901            } else {
1902                mCustomResolverComponentName = ComponentName.unflattenFromString(
1903                        customResolverActivity);
1904            }
1905
1906            long startTime = SystemClock.uptimeMillis();
1907
1908            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1909                    startTime);
1910
1911            // Set flag to monitor and not change apk file paths when
1912            // scanning install directories.
1913            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1914
1915            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1916
1917            /**
1918             * Add everything in the in the boot class path to the
1919             * list of process files because dexopt will have been run
1920             * if necessary during zygote startup.
1921             */
1922            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1923            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1924
1925            if (bootClassPath != null) {
1926                String[] bootClassPathElements = splitString(bootClassPath, ':');
1927                for (String element : bootClassPathElements) {
1928                    alreadyDexOpted.add(element);
1929                }
1930            } else {
1931                Slog.w(TAG, "No BOOTCLASSPATH found!");
1932            }
1933
1934            if (systemServerClassPath != null) {
1935                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1936                for (String element : systemServerClassPathElements) {
1937                    alreadyDexOpted.add(element);
1938                }
1939            } else {
1940                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1941            }
1942
1943            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1944            final String[] dexCodeInstructionSets =
1945                    getDexCodeInstructionSets(
1946                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1947
1948            /**
1949             * Ensure all external libraries have had dexopt run on them.
1950             */
1951            if (mSharedLibraries.size() > 0) {
1952                // NOTE: For now, we're compiling these system "shared libraries"
1953                // (and framework jars) into all available architectures. It's possible
1954                // to compile them only when we come across an app that uses them (there's
1955                // already logic for that in scanPackageLI) but that adds some complexity.
1956                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1957                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1958                        final String lib = libEntry.path;
1959                        if (lib == null) {
1960                            continue;
1961                        }
1962
1963                        try {
1964                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1965                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1966                                alreadyDexOpted.add(lib);
1967                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1968                            }
1969                        } catch (FileNotFoundException e) {
1970                            Slog.w(TAG, "Library not found: " + lib);
1971                        } catch (IOException e) {
1972                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1973                                    + e.getMessage());
1974                        }
1975                    }
1976                }
1977            }
1978
1979            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1980
1981            // Gross hack for now: we know this file doesn't contain any
1982            // code, so don't dexopt it to avoid the resulting log spew.
1983            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1984
1985            // Gross hack for now: we know this file is only part of
1986            // the boot class path for art, so don't dexopt it to
1987            // avoid the resulting log spew.
1988            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1989
1990            /**
1991             * There are a number of commands implemented in Java, which
1992             * we currently need to do the dexopt on so that they can be
1993             * run from a non-root shell.
1994             */
1995            String[] frameworkFiles = frameworkDir.list();
1996            if (frameworkFiles != null) {
1997                // TODO: We could compile these only for the most preferred ABI. We should
1998                // first double check that the dex files for these commands are not referenced
1999                // by other system apps.
2000                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2001                    for (int i=0; i<frameworkFiles.length; i++) {
2002                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2003                        String path = libPath.getPath();
2004                        // Skip the file if we already did it.
2005                        if (alreadyDexOpted.contains(path)) {
2006                            continue;
2007                        }
2008                        // Skip the file if it is not a type we want to dexopt.
2009                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2010                            continue;
2011                        }
2012                        try {
2013                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2014                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2015                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2016                            }
2017                        } catch (FileNotFoundException e) {
2018                            Slog.w(TAG, "Jar not found: " + path);
2019                        } catch (IOException e) {
2020                            Slog.w(TAG, "Exception reading jar: " + path, e);
2021                        }
2022                    }
2023                }
2024            }
2025
2026            // Collect vendor overlay packages.
2027            // (Do this before scanning any apps.)
2028            // For security and version matching reason, only consider
2029            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2030            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2031            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2032                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2033
2034            // Find base frameworks (resource packages without code).
2035            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR
2037                    | PackageParser.PARSE_IS_PRIVILEGED,
2038                    scanFlags | SCAN_NO_DEX, 0);
2039
2040            // Collected privileged system packages.
2041            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2042            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2043                    | PackageParser.PARSE_IS_SYSTEM_DIR
2044                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2045
2046            // Collect ordinary system packages.
2047            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2048            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2049                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2050
2051            // Collect all vendor packages.
2052            File vendorAppDir = new File("/vendor/app");
2053            try {
2054                vendorAppDir = vendorAppDir.getCanonicalFile();
2055            } catch (IOException e) {
2056                // failed to look up canonical path, continue with original one
2057            }
2058            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2059                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2060
2061            // Collect all OEM packages.
2062            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2063            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2064                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2065
2066            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2067            mInstaller.moveFiles();
2068
2069            // Prune any system packages that no longer exist.
2070            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2071            if (!mOnlyCore) {
2072                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2073                while (psit.hasNext()) {
2074                    PackageSetting ps = psit.next();
2075
2076                    /*
2077                     * If this is not a system app, it can't be a
2078                     * disable system app.
2079                     */
2080                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2081                        continue;
2082                    }
2083
2084                    /*
2085                     * If the package is scanned, it's not erased.
2086                     */
2087                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2088                    if (scannedPkg != null) {
2089                        /*
2090                         * If the system app is both scanned and in the
2091                         * disabled packages list, then it must have been
2092                         * added via OTA. Remove it from the currently
2093                         * scanned package so the previously user-installed
2094                         * application can be scanned.
2095                         */
2096                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2097                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2098                                    + ps.name + "; removing system app.  Last known codePath="
2099                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2100                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2101                                    + scannedPkg.mVersionCode);
2102                            removePackageLI(ps, true);
2103                            mExpectingBetter.put(ps.name, ps.codePath);
2104                        }
2105
2106                        continue;
2107                    }
2108
2109                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2110                        psit.remove();
2111                        logCriticalInfo(Log.WARN, "System package " + ps.name
2112                                + " no longer exists; wiping its data");
2113                        removeDataDirsLI(null, ps.name);
2114                    } else {
2115                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2116                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2117                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2118                        }
2119                    }
2120                }
2121            }
2122
2123            //look for any incomplete package installations
2124            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2125            //clean up list
2126            for(int i = 0; i < deletePkgsList.size(); i++) {
2127                //clean up here
2128                cleanupInstallFailedPackage(deletePkgsList.get(i));
2129            }
2130            //delete tmp files
2131            deleteTempPackageFiles();
2132
2133            // Remove any shared userIDs that have no associated packages
2134            mSettings.pruneSharedUsersLPw();
2135
2136            if (!mOnlyCore) {
2137                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2138                        SystemClock.uptimeMillis());
2139                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2140
2141                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2142                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2143
2144                /**
2145                 * Remove disable package settings for any updated system
2146                 * apps that were removed via an OTA. If they're not a
2147                 * previously-updated app, remove them completely.
2148                 * Otherwise, just revoke their system-level permissions.
2149                 */
2150                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2151                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2152                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2153
2154                    String msg;
2155                    if (deletedPkg == null) {
2156                        msg = "Updated system package " + deletedAppName
2157                                + " no longer exists; wiping its data";
2158                        removeDataDirsLI(null, deletedAppName);
2159                    } else {
2160                        msg = "Updated system app + " + deletedAppName
2161                                + " no longer present; removing system privileges for "
2162                                + deletedAppName;
2163
2164                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2165
2166                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2167                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2168                    }
2169                    logCriticalInfo(Log.WARN, msg);
2170                }
2171
2172                /**
2173                 * Make sure all system apps that we expected to appear on
2174                 * the userdata partition actually showed up. If they never
2175                 * appeared, crawl back and revive the system version.
2176                 */
2177                for (int i = 0; i < mExpectingBetter.size(); i++) {
2178                    final String packageName = mExpectingBetter.keyAt(i);
2179                    if (!mPackages.containsKey(packageName)) {
2180                        final File scanFile = mExpectingBetter.valueAt(i);
2181
2182                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2183                                + " but never showed up; reverting to system");
2184
2185                        final int reparseFlags;
2186                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2187                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2188                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2189                                    | PackageParser.PARSE_IS_PRIVILEGED;
2190                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2191                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2192                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2193                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2194                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2195                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2196                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2197                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2198                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2199                        } else {
2200                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2201                            continue;
2202                        }
2203
2204                        mSettings.enableSystemPackageLPw(packageName);
2205
2206                        try {
2207                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2208                        } catch (PackageManagerException e) {
2209                            Slog.e(TAG, "Failed to parse original system package: "
2210                                    + e.getMessage());
2211                        }
2212                    }
2213                }
2214            }
2215            mExpectingBetter.clear();
2216
2217            // Now that we know all of the shared libraries, update all clients to have
2218            // the correct library paths.
2219            updateAllSharedLibrariesLPw();
2220
2221            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2222                // NOTE: We ignore potential failures here during a system scan (like
2223                // the rest of the commands above) because there's precious little we
2224                // can do about it. A settings error is reported, though.
2225                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2226                        false /* force dexopt */, false /* defer dexopt */);
2227            }
2228
2229            // Now that we know all the packages we are keeping,
2230            // read and update their last usage times.
2231            mPackageUsage.readLP();
2232
2233            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2234                    SystemClock.uptimeMillis());
2235            Slog.i(TAG, "Time to scan packages: "
2236                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2237                    + " seconds");
2238
2239            // If the platform SDK has changed since the last time we booted,
2240            // we need to re-grant app permission to catch any new ones that
2241            // appear.  This is really a hack, and means that apps can in some
2242            // cases get permissions that the user didn't initially explicitly
2243            // allow...  it would be nice to have some better way to handle
2244            // this situation.
2245            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2246                    != mSdkVersion;
2247            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2248                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2249                    + "; regranting permissions for internal storage");
2250            mSettings.mInternalSdkPlatform = mSdkVersion;
2251
2252            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2253                    | (regrantPermissions
2254                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2255                            : 0));
2256
2257            // If this is the first boot, and it is a normal boot, then
2258            // we need to initialize the default preferred apps.
2259            if (!mRestoredSettings && !onlyCore) {
2260                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2261                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2262                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2263            }
2264
2265            // If this is first boot after an OTA, and a normal boot, then
2266            // we need to clear code cache directories.
2267            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2268            if (mIsUpgrade && !onlyCore) {
2269                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2270                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2271                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2272                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2273                }
2274                mSettings.mFingerprint = Build.FINGERPRINT;
2275            }
2276
2277            checkDefaultBrowser();
2278
2279            // All the changes are done during package scanning.
2280            mSettings.updateInternalDatabaseVersion();
2281
2282            // can downgrade to reader
2283            mSettings.writeLPr();
2284
2285            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2286                    SystemClock.uptimeMillis());
2287
2288            mRequiredVerifierPackage = getRequiredVerifierLPr();
2289            mRequiredInstallerPackage = getRequiredInstallerLPr();
2290
2291            mInstallerService = new PackageInstallerService(context, this);
2292
2293            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2294            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2295                    mIntentFilterVerifierComponent);
2296
2297        } // synchronized (mPackages)
2298        } // synchronized (mInstallLock)
2299
2300        // Now after opening every single application zip, make sure they
2301        // are all flushed.  Not really needed, but keeps things nice and
2302        // tidy.
2303        Runtime.getRuntime().gc();
2304
2305        // Expose private service for system components to use.
2306        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2307    }
2308
2309    @Override
2310    public boolean isFirstBoot() {
2311        return !mRestoredSettings;
2312    }
2313
2314    @Override
2315    public boolean isOnlyCoreApps() {
2316        return mOnlyCore;
2317    }
2318
2319    @Override
2320    public boolean isUpgrade() {
2321        return mIsUpgrade;
2322    }
2323
2324    private String getRequiredVerifierLPr() {
2325        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2326        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2327                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2328
2329        String requiredVerifier = null;
2330
2331        final int N = receivers.size();
2332        for (int i = 0; i < N; i++) {
2333            final ResolveInfo info = receivers.get(i);
2334
2335            if (info.activityInfo == null) {
2336                continue;
2337            }
2338
2339            final String packageName = info.activityInfo.packageName;
2340
2341            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2342                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2343                continue;
2344            }
2345
2346            if (requiredVerifier != null) {
2347                throw new RuntimeException("There can be only one required verifier");
2348            }
2349
2350            requiredVerifier = packageName;
2351        }
2352
2353        return requiredVerifier;
2354    }
2355
2356    private String getRequiredInstallerLPr() {
2357        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2358        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2359        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2360
2361        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2362                PACKAGE_MIME_TYPE, 0, 0);
2363
2364        String requiredInstaller = null;
2365
2366        final int N = installers.size();
2367        for (int i = 0; i < N; i++) {
2368            final ResolveInfo info = installers.get(i);
2369            final String packageName = info.activityInfo.packageName;
2370
2371            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2372                continue;
2373            }
2374
2375            if (requiredInstaller != null) {
2376                throw new RuntimeException("There must be one required installer");
2377            }
2378
2379            requiredInstaller = packageName;
2380        }
2381
2382        if (requiredInstaller == null) {
2383            throw new RuntimeException("There must be one required installer");
2384        }
2385
2386        return requiredInstaller;
2387    }
2388
2389    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2390        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2391        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2392                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2393
2394        ComponentName verifierComponentName = null;
2395
2396        int priority = -1000;
2397        final int N = receivers.size();
2398        for (int i = 0; i < N; i++) {
2399            final ResolveInfo info = receivers.get(i);
2400
2401            if (info.activityInfo == null) {
2402                continue;
2403            }
2404
2405            final String packageName = info.activityInfo.packageName;
2406
2407            final PackageSetting ps = mSettings.mPackages.get(packageName);
2408            if (ps == null) {
2409                continue;
2410            }
2411
2412            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2413                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2414                continue;
2415            }
2416
2417            // Select the IntentFilterVerifier with the highest priority
2418            if (priority < info.priority) {
2419                priority = info.priority;
2420                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2421                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2422                        + verifierComponentName + " with priority: " + info.priority);
2423            }
2424        }
2425
2426        return verifierComponentName;
2427    }
2428
2429    private void primeDomainVerificationsLPw(int userId) {
2430        if (DEBUG_DOMAIN_VERIFICATION) {
2431            Slog.d(TAG, "Priming domain verifications in user " + userId);
2432        }
2433
2434        SystemConfig systemConfig = SystemConfig.getInstance();
2435        ArraySet<String> packages = systemConfig.getLinkedApps();
2436        ArraySet<String> domains = new ArraySet<String>();
2437
2438        for (String packageName : packages) {
2439            PackageParser.Package pkg = mPackages.get(packageName);
2440            if (pkg != null) {
2441                if (!pkg.isSystemApp()) {
2442                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2443                    continue;
2444                }
2445
2446                domains.clear();
2447                for (PackageParser.Activity a : pkg.activities) {
2448                    for (ActivityIntentInfo filter : a.intents) {
2449                        if (hasValidDomains(filter)) {
2450                            domains.addAll(filter.getHostsList());
2451                        }
2452                    }
2453                }
2454
2455                if (domains.size() > 0) {
2456                    if (DEBUG_DOMAIN_VERIFICATION) {
2457                        Slog.v(TAG, "      + " + packageName);
2458                    }
2459                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2460                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2461                    // and then 'always' in the per-user state actually used for intent resolution.
2462                    final IntentFilterVerificationInfo ivi;
2463                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2464                            new ArrayList<String>(domains));
2465                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2466                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2467                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2468                } else {
2469                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2470                            + "' does not handle web links");
2471                }
2472            } else {
2473                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2474            }
2475        }
2476
2477        scheduleWritePackageRestrictionsLocked(userId);
2478        scheduleWriteSettingsLocked();
2479    }
2480
2481    private void applyFactoryDefaultBrowserLPw(int userId) {
2482        // The default browser app's package name is stored in a string resource,
2483        // with a product-specific overlay used for vendor customization.
2484        String browserPkg = mContext.getResources().getString(
2485                com.android.internal.R.string.default_browser);
2486        if (!TextUtils.isEmpty(browserPkg)) {
2487            // non-empty string => required to be a known package
2488            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2489            if (ps == null) {
2490                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2491                browserPkg = null;
2492            } else {
2493                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2494            }
2495        }
2496
2497        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2498        // default.  If there's more than one, just leave everything alone.
2499        if (browserPkg == null) {
2500            calculateDefaultBrowserLPw(userId);
2501        }
2502    }
2503
2504    private void calculateDefaultBrowserLPw(int userId) {
2505        List<String> allBrowsers = resolveAllBrowserApps(userId);
2506        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2507        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2508    }
2509
2510    private List<String> resolveAllBrowserApps(int userId) {
2511        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2512        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2513                PackageManager.MATCH_ALL, userId);
2514
2515        final int count = list.size();
2516        List<String> result = new ArrayList<String>(count);
2517        for (int i=0; i<count; i++) {
2518            ResolveInfo info = list.get(i);
2519            if (info.activityInfo == null
2520                    || !info.handleAllWebDataURI
2521                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2522                    || result.contains(info.activityInfo.packageName)) {
2523                continue;
2524            }
2525            result.add(info.activityInfo.packageName);
2526        }
2527
2528        return result;
2529    }
2530
2531    private boolean packageIsBrowser(String packageName, int userId) {
2532        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2533                PackageManager.MATCH_ALL, userId);
2534        final int N = list.size();
2535        for (int i = 0; i < N; i++) {
2536            ResolveInfo info = list.get(i);
2537            if (packageName.equals(info.activityInfo.packageName)) {
2538                return true;
2539            }
2540        }
2541        return false;
2542    }
2543
2544    private void checkDefaultBrowser() {
2545        final int myUserId = UserHandle.myUserId();
2546        final String packageName = getDefaultBrowserPackageName(myUserId);
2547        if (packageName != null) {
2548            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2549            if (info == null) {
2550                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2551                synchronized (mPackages) {
2552                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2553                }
2554            }
2555        }
2556    }
2557
2558    @Override
2559    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2560            throws RemoteException {
2561        try {
2562            return super.onTransact(code, data, reply, flags);
2563        } catch (RuntimeException e) {
2564            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2565                Slog.wtf(TAG, "Package Manager Crash", e);
2566            }
2567            throw e;
2568        }
2569    }
2570
2571    void cleanupInstallFailedPackage(PackageSetting ps) {
2572        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2573
2574        removeDataDirsLI(ps.volumeUuid, ps.name);
2575        if (ps.codePath != null) {
2576            if (ps.codePath.isDirectory()) {
2577                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2578            } else {
2579                ps.codePath.delete();
2580            }
2581        }
2582        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2583            if (ps.resourcePath.isDirectory()) {
2584                FileUtils.deleteContents(ps.resourcePath);
2585            }
2586            ps.resourcePath.delete();
2587        }
2588        mSettings.removePackageLPw(ps.name);
2589    }
2590
2591    static int[] appendInts(int[] cur, int[] add) {
2592        if (add == null) return cur;
2593        if (cur == null) return add;
2594        final int N = add.length;
2595        for (int i=0; i<N; i++) {
2596            cur = appendInt(cur, add[i]);
2597        }
2598        return cur;
2599    }
2600
2601    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2602        if (!sUserManager.exists(userId)) return null;
2603        final PackageSetting ps = (PackageSetting) p.mExtras;
2604        if (ps == null) {
2605            return null;
2606        }
2607
2608        final PermissionsState permissionsState = ps.getPermissionsState();
2609
2610        final int[] gids = permissionsState.computeGids(userId);
2611        final Set<String> permissions = permissionsState.getPermissions(userId);
2612        final PackageUserState state = ps.readUserState(userId);
2613
2614        return PackageParser.generatePackageInfo(p, gids, flags,
2615                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2616    }
2617
2618    @Override
2619    public boolean isPackageFrozen(String packageName) {
2620        synchronized (mPackages) {
2621            final PackageSetting ps = mSettings.mPackages.get(packageName);
2622            if (ps != null) {
2623                return ps.frozen;
2624            }
2625        }
2626        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2627        return true;
2628    }
2629
2630    @Override
2631    public boolean isPackageAvailable(String packageName, int userId) {
2632        if (!sUserManager.exists(userId)) return false;
2633        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2634        synchronized (mPackages) {
2635            PackageParser.Package p = mPackages.get(packageName);
2636            if (p != null) {
2637                final PackageSetting ps = (PackageSetting) p.mExtras;
2638                if (ps != null) {
2639                    final PackageUserState state = ps.readUserState(userId);
2640                    if (state != null) {
2641                        return PackageParser.isAvailable(state);
2642                    }
2643                }
2644            }
2645        }
2646        return false;
2647    }
2648
2649    @Override
2650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2651        if (!sUserManager.exists(userId)) return null;
2652        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2653        // reader
2654        synchronized (mPackages) {
2655            PackageParser.Package p = mPackages.get(packageName);
2656            if (DEBUG_PACKAGE_INFO)
2657                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2658            if (p != null) {
2659                return generatePackageInfo(p, flags, userId);
2660            }
2661            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2662                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2663            }
2664        }
2665        return null;
2666    }
2667
2668    @Override
2669    public String[] currentToCanonicalPackageNames(String[] names) {
2670        String[] out = new String[names.length];
2671        // reader
2672        synchronized (mPackages) {
2673            for (int i=names.length-1; i>=0; i--) {
2674                PackageSetting ps = mSettings.mPackages.get(names[i]);
2675                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2676            }
2677        }
2678        return out;
2679    }
2680
2681    @Override
2682    public String[] canonicalToCurrentPackageNames(String[] names) {
2683        String[] out = new String[names.length];
2684        // reader
2685        synchronized (mPackages) {
2686            for (int i=names.length-1; i>=0; i--) {
2687                String cur = mSettings.mRenamedPackages.get(names[i]);
2688                out[i] = cur != null ? cur : names[i];
2689            }
2690        }
2691        return out;
2692    }
2693
2694    @Override
2695    public int getPackageUid(String packageName, int userId) {
2696        if (!sUserManager.exists(userId)) return -1;
2697        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2698
2699        // reader
2700        synchronized (mPackages) {
2701            PackageParser.Package p = mPackages.get(packageName);
2702            if(p != null) {
2703                return UserHandle.getUid(userId, p.applicationInfo.uid);
2704            }
2705            PackageSetting ps = mSettings.mPackages.get(packageName);
2706            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2707                return -1;
2708            }
2709            p = ps.pkg;
2710            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2711        }
2712    }
2713
2714    @Override
2715    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2716        if (!sUserManager.exists(userId)) {
2717            return null;
2718        }
2719
2720        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2721                "getPackageGids");
2722
2723        // reader
2724        synchronized (mPackages) {
2725            PackageParser.Package p = mPackages.get(packageName);
2726            if (DEBUG_PACKAGE_INFO) {
2727                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2728            }
2729            if (p != null) {
2730                PackageSetting ps = (PackageSetting) p.mExtras;
2731                return ps.getPermissionsState().computeGids(userId);
2732            }
2733        }
2734
2735        return null;
2736    }
2737
2738    static PermissionInfo generatePermissionInfo(
2739            BasePermission bp, int flags) {
2740        if (bp.perm != null) {
2741            return PackageParser.generatePermissionInfo(bp.perm, flags);
2742        }
2743        PermissionInfo pi = new PermissionInfo();
2744        pi.name = bp.name;
2745        pi.packageName = bp.sourcePackage;
2746        pi.nonLocalizedLabel = bp.name;
2747        pi.protectionLevel = bp.protectionLevel;
2748        return pi;
2749    }
2750
2751    @Override
2752    public PermissionInfo getPermissionInfo(String name, int flags) {
2753        // reader
2754        synchronized (mPackages) {
2755            final BasePermission p = mSettings.mPermissions.get(name);
2756            if (p != null) {
2757                return generatePermissionInfo(p, flags);
2758            }
2759            return null;
2760        }
2761    }
2762
2763    @Override
2764    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2765        // reader
2766        synchronized (mPackages) {
2767            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2768            for (BasePermission p : mSettings.mPermissions.values()) {
2769                if (group == null) {
2770                    if (p.perm == null || p.perm.info.group == null) {
2771                        out.add(generatePermissionInfo(p, flags));
2772                    }
2773                } else {
2774                    if (p.perm != null && group.equals(p.perm.info.group)) {
2775                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2776                    }
2777                }
2778            }
2779
2780            if (out.size() > 0) {
2781                return out;
2782            }
2783            return mPermissionGroups.containsKey(group) ? out : null;
2784        }
2785    }
2786
2787    @Override
2788    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2789        // reader
2790        synchronized (mPackages) {
2791            return PackageParser.generatePermissionGroupInfo(
2792                    mPermissionGroups.get(name), flags);
2793        }
2794    }
2795
2796    @Override
2797    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2798        // reader
2799        synchronized (mPackages) {
2800            final int N = mPermissionGroups.size();
2801            ArrayList<PermissionGroupInfo> out
2802                    = new ArrayList<PermissionGroupInfo>(N);
2803            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2804                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2805            }
2806            return out;
2807        }
2808    }
2809
2810    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2811            int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        PackageSetting ps = mSettings.mPackages.get(packageName);
2814        if (ps != null) {
2815            if (ps.pkg == null) {
2816                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2817                        flags, userId);
2818                if (pInfo != null) {
2819                    return pInfo.applicationInfo;
2820                }
2821                return null;
2822            }
2823            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2824                    ps.readUserState(userId), userId);
2825        }
2826        return null;
2827    }
2828
2829    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2830            int userId) {
2831        if (!sUserManager.exists(userId)) return null;
2832        PackageSetting ps = mSettings.mPackages.get(packageName);
2833        if (ps != null) {
2834            PackageParser.Package pkg = ps.pkg;
2835            if (pkg == null) {
2836                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2837                    return null;
2838                }
2839                // Only data remains, so we aren't worried about code paths
2840                pkg = new PackageParser.Package(packageName);
2841                pkg.applicationInfo.packageName = packageName;
2842                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2843                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2844                pkg.applicationInfo.dataDir = Environment
2845                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2846                        .getAbsolutePath();
2847                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2848                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2849            }
2850            return generatePackageInfo(pkg, flags, userId);
2851        }
2852        return null;
2853    }
2854
2855    @Override
2856    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2857        if (!sUserManager.exists(userId)) return null;
2858        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2859        // writer
2860        synchronized (mPackages) {
2861            PackageParser.Package p = mPackages.get(packageName);
2862            if (DEBUG_PACKAGE_INFO) Log.v(
2863                    TAG, "getApplicationInfo " + packageName
2864                    + ": " + p);
2865            if (p != null) {
2866                PackageSetting ps = mSettings.mPackages.get(packageName);
2867                if (ps == null) return null;
2868                // Note: isEnabledLP() does not apply here - always return info
2869                return PackageParser.generateApplicationInfo(
2870                        p, flags, ps.readUserState(userId), userId);
2871            }
2872            if ("android".equals(packageName)||"system".equals(packageName)) {
2873                return mAndroidApplication;
2874            }
2875            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2876                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2877            }
2878        }
2879        return null;
2880    }
2881
2882    @Override
2883    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2884            final IPackageDataObserver observer) {
2885        mContext.enforceCallingOrSelfPermission(
2886                android.Manifest.permission.CLEAR_APP_CACHE, null);
2887        // Queue up an async operation since clearing cache may take a little while.
2888        mHandler.post(new Runnable() {
2889            public void run() {
2890                mHandler.removeCallbacks(this);
2891                int retCode = -1;
2892                synchronized (mInstallLock) {
2893                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2894                    if (retCode < 0) {
2895                        Slog.w(TAG, "Couldn't clear application caches");
2896                    }
2897                }
2898                if (observer != null) {
2899                    try {
2900                        observer.onRemoveCompleted(null, (retCode >= 0));
2901                    } catch (RemoteException e) {
2902                        Slog.w(TAG, "RemoveException when invoking call back");
2903                    }
2904                }
2905            }
2906        });
2907    }
2908
2909    @Override
2910    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2911            final IntentSender pi) {
2912        mContext.enforceCallingOrSelfPermission(
2913                android.Manifest.permission.CLEAR_APP_CACHE, null);
2914        // Queue up an async operation since clearing cache may take a little while.
2915        mHandler.post(new Runnable() {
2916            public void run() {
2917                mHandler.removeCallbacks(this);
2918                int retCode = -1;
2919                synchronized (mInstallLock) {
2920                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2921                    if (retCode < 0) {
2922                        Slog.w(TAG, "Couldn't clear application caches");
2923                    }
2924                }
2925                if(pi != null) {
2926                    try {
2927                        // Callback via pending intent
2928                        int code = (retCode >= 0) ? 1 : 0;
2929                        pi.sendIntent(null, code, null,
2930                                null, null);
2931                    } catch (SendIntentException e1) {
2932                        Slog.i(TAG, "Failed to send pending intent");
2933                    }
2934                }
2935            }
2936        });
2937    }
2938
2939    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2940        synchronized (mInstallLock) {
2941            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2942                throw new IOException("Failed to free enough space");
2943            }
2944        }
2945    }
2946
2947    @Override
2948    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2949        if (!sUserManager.exists(userId)) return null;
2950        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2951        synchronized (mPackages) {
2952            PackageParser.Activity a = mActivities.mActivities.get(component);
2953
2954            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2955            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2956                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2957                if (ps == null) return null;
2958                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2959                        userId);
2960            }
2961            if (mResolveComponentName.equals(component)) {
2962                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2963                        new PackageUserState(), userId);
2964            }
2965        }
2966        return null;
2967    }
2968
2969    @Override
2970    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2971            String resolvedType) {
2972        synchronized (mPackages) {
2973            PackageParser.Activity a = mActivities.mActivities.get(component);
2974            if (a == null) {
2975                return false;
2976            }
2977            for (int i=0; i<a.intents.size(); i++) {
2978                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2979                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2980                    return true;
2981                }
2982            }
2983            return false;
2984        }
2985    }
2986
2987    @Override
2988    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2989        if (!sUserManager.exists(userId)) return null;
2990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2991        synchronized (mPackages) {
2992            PackageParser.Activity a = mReceivers.mActivities.get(component);
2993            if (DEBUG_PACKAGE_INFO) Log.v(
2994                TAG, "getReceiverInfo " + component + ": " + a);
2995            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2996                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2997                if (ps == null) return null;
2998                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2999                        userId);
3000            }
3001        }
3002        return null;
3003    }
3004
3005    @Override
3006    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3007        if (!sUserManager.exists(userId)) return null;
3008        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3009        synchronized (mPackages) {
3010            PackageParser.Service s = mServices.mServices.get(component);
3011            if (DEBUG_PACKAGE_INFO) Log.v(
3012                TAG, "getServiceInfo " + component + ": " + s);
3013            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3014                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3015                if (ps == null) return null;
3016                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3017                        userId);
3018            }
3019        }
3020        return null;
3021    }
3022
3023    @Override
3024    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3025        if (!sUserManager.exists(userId)) return null;
3026        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3027        synchronized (mPackages) {
3028            PackageParser.Provider p = mProviders.mProviders.get(component);
3029            if (DEBUG_PACKAGE_INFO) Log.v(
3030                TAG, "getProviderInfo " + component + ": " + p);
3031            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3032                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3033                if (ps == null) return null;
3034                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3035                        userId);
3036            }
3037        }
3038        return null;
3039    }
3040
3041    @Override
3042    public String[] getSystemSharedLibraryNames() {
3043        Set<String> libSet;
3044        synchronized (mPackages) {
3045            libSet = mSharedLibraries.keySet();
3046            int size = libSet.size();
3047            if (size > 0) {
3048                String[] libs = new String[size];
3049                libSet.toArray(libs);
3050                return libs;
3051            }
3052        }
3053        return null;
3054    }
3055
3056    /**
3057     * @hide
3058     */
3059    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3060        synchronized (mPackages) {
3061            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3062            if (lib != null && lib.apk != null) {
3063                return mPackages.get(lib.apk);
3064            }
3065        }
3066        return null;
3067    }
3068
3069    @Override
3070    public FeatureInfo[] getSystemAvailableFeatures() {
3071        Collection<FeatureInfo> featSet;
3072        synchronized (mPackages) {
3073            featSet = mAvailableFeatures.values();
3074            int size = featSet.size();
3075            if (size > 0) {
3076                FeatureInfo[] features = new FeatureInfo[size+1];
3077                featSet.toArray(features);
3078                FeatureInfo fi = new FeatureInfo();
3079                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3080                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3081                features[size] = fi;
3082                return features;
3083            }
3084        }
3085        return null;
3086    }
3087
3088    @Override
3089    public boolean hasSystemFeature(String name) {
3090        synchronized (mPackages) {
3091            return mAvailableFeatures.containsKey(name);
3092        }
3093    }
3094
3095    private void checkValidCaller(int uid, int userId) {
3096        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3097            return;
3098
3099        throw new SecurityException("Caller uid=" + uid
3100                + " is not privileged to communicate with user=" + userId);
3101    }
3102
3103    @Override
3104    public int checkPermission(String permName, String pkgName, int userId) {
3105        if (!sUserManager.exists(userId)) {
3106            return PackageManager.PERMISSION_DENIED;
3107        }
3108
3109        synchronized (mPackages) {
3110            final PackageParser.Package p = mPackages.get(pkgName);
3111            if (p != null && p.mExtras != null) {
3112                final PackageSetting ps = (PackageSetting) p.mExtras;
3113                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3114                    return PackageManager.PERMISSION_GRANTED;
3115                }
3116            }
3117        }
3118
3119        return PackageManager.PERMISSION_DENIED;
3120    }
3121
3122    @Override
3123    public int checkUidPermission(String permName, int uid) {
3124        final int userId = UserHandle.getUserId(uid);
3125
3126        if (!sUserManager.exists(userId)) {
3127            return PackageManager.PERMISSION_DENIED;
3128        }
3129
3130        synchronized (mPackages) {
3131            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3132            if (obj != null) {
3133                final SettingBase ps = (SettingBase) obj;
3134                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3135                    return PackageManager.PERMISSION_GRANTED;
3136                }
3137            } else {
3138                ArraySet<String> perms = mSystemPermissions.get(uid);
3139                if (perms != null && perms.contains(permName)) {
3140                    return PackageManager.PERMISSION_GRANTED;
3141                }
3142            }
3143        }
3144
3145        return PackageManager.PERMISSION_DENIED;
3146    }
3147
3148    @Override
3149    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3150        if (UserHandle.getCallingUserId() != userId) {
3151            mContext.enforceCallingPermission(
3152                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3153                    "isPermissionRevokedByPolicy for user " + userId);
3154        }
3155
3156        if (checkPermission(permission, packageName, userId)
3157                == PackageManager.PERMISSION_GRANTED) {
3158            return false;
3159        }
3160
3161        final long identity = Binder.clearCallingIdentity();
3162        try {
3163            final int flags = getPermissionFlags(permission, packageName, userId);
3164            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3165        } finally {
3166            Binder.restoreCallingIdentity(identity);
3167        }
3168    }
3169
3170    /**
3171     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3172     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3173     * @param checkShell TODO(yamasani):
3174     * @param message the message to log on security exception
3175     */
3176    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3177            boolean checkShell, String message) {
3178        if (userId < 0) {
3179            throw new IllegalArgumentException("Invalid userId " + userId);
3180        }
3181        if (checkShell) {
3182            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3183        }
3184        if (userId == UserHandle.getUserId(callingUid)) return;
3185        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3186            if (requireFullPermission) {
3187                mContext.enforceCallingOrSelfPermission(
3188                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3189            } else {
3190                try {
3191                    mContext.enforceCallingOrSelfPermission(
3192                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3193                } catch (SecurityException se) {
3194                    mContext.enforceCallingOrSelfPermission(
3195                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3196                }
3197            }
3198        }
3199    }
3200
3201    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3202        if (callingUid == Process.SHELL_UID) {
3203            if (userHandle >= 0
3204                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3205                throw new SecurityException("Shell does not have permission to access user "
3206                        + userHandle);
3207            } else if (userHandle < 0) {
3208                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3209                        + Debug.getCallers(3));
3210            }
3211        }
3212    }
3213
3214    private BasePermission findPermissionTreeLP(String permName) {
3215        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3216            if (permName.startsWith(bp.name) &&
3217                    permName.length() > bp.name.length() &&
3218                    permName.charAt(bp.name.length()) == '.') {
3219                return bp;
3220            }
3221        }
3222        return null;
3223    }
3224
3225    private BasePermission checkPermissionTreeLP(String permName) {
3226        if (permName != null) {
3227            BasePermission bp = findPermissionTreeLP(permName);
3228            if (bp != null) {
3229                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3230                    return bp;
3231                }
3232                throw new SecurityException("Calling uid "
3233                        + Binder.getCallingUid()
3234                        + " is not allowed to add to permission tree "
3235                        + bp.name + " owned by uid " + bp.uid);
3236            }
3237        }
3238        throw new SecurityException("No permission tree found for " + permName);
3239    }
3240
3241    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3242        if (s1 == null) {
3243            return s2 == null;
3244        }
3245        if (s2 == null) {
3246            return false;
3247        }
3248        if (s1.getClass() != s2.getClass()) {
3249            return false;
3250        }
3251        return s1.equals(s2);
3252    }
3253
3254    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3255        if (pi1.icon != pi2.icon) return false;
3256        if (pi1.logo != pi2.logo) return false;
3257        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3258        if (!compareStrings(pi1.name, pi2.name)) return false;
3259        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3260        // We'll take care of setting this one.
3261        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3262        // These are not currently stored in settings.
3263        //if (!compareStrings(pi1.group, pi2.group)) return false;
3264        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3265        //if (pi1.labelRes != pi2.labelRes) return false;
3266        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3267        return true;
3268    }
3269
3270    int permissionInfoFootprint(PermissionInfo info) {
3271        int size = info.name.length();
3272        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3273        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3274        return size;
3275    }
3276
3277    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3278        int size = 0;
3279        for (BasePermission perm : mSettings.mPermissions.values()) {
3280            if (perm.uid == tree.uid) {
3281                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3282            }
3283        }
3284        return size;
3285    }
3286
3287    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3288        // We calculate the max size of permissions defined by this uid and throw
3289        // if that plus the size of 'info' would exceed our stated maximum.
3290        if (tree.uid != Process.SYSTEM_UID) {
3291            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3292            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3293                throw new SecurityException("Permission tree size cap exceeded");
3294            }
3295        }
3296    }
3297
3298    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3299        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3300            throw new SecurityException("Label must be specified in permission");
3301        }
3302        BasePermission tree = checkPermissionTreeLP(info.name);
3303        BasePermission bp = mSettings.mPermissions.get(info.name);
3304        boolean added = bp == null;
3305        boolean changed = true;
3306        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3307        if (added) {
3308            enforcePermissionCapLocked(info, tree);
3309            bp = new BasePermission(info.name, tree.sourcePackage,
3310                    BasePermission.TYPE_DYNAMIC);
3311        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3312            throw new SecurityException(
3313                    "Not allowed to modify non-dynamic permission "
3314                    + info.name);
3315        } else {
3316            if (bp.protectionLevel == fixedLevel
3317                    && bp.perm.owner.equals(tree.perm.owner)
3318                    && bp.uid == tree.uid
3319                    && comparePermissionInfos(bp.perm.info, info)) {
3320                changed = false;
3321            }
3322        }
3323        bp.protectionLevel = fixedLevel;
3324        info = new PermissionInfo(info);
3325        info.protectionLevel = fixedLevel;
3326        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3327        bp.perm.info.packageName = tree.perm.info.packageName;
3328        bp.uid = tree.uid;
3329        if (added) {
3330            mSettings.mPermissions.put(info.name, bp);
3331        }
3332        if (changed) {
3333            if (!async) {
3334                mSettings.writeLPr();
3335            } else {
3336                scheduleWriteSettingsLocked();
3337            }
3338        }
3339        return added;
3340    }
3341
3342    @Override
3343    public boolean addPermission(PermissionInfo info) {
3344        synchronized (mPackages) {
3345            return addPermissionLocked(info, false);
3346        }
3347    }
3348
3349    @Override
3350    public boolean addPermissionAsync(PermissionInfo info) {
3351        synchronized (mPackages) {
3352            return addPermissionLocked(info, true);
3353        }
3354    }
3355
3356    @Override
3357    public void removePermission(String name) {
3358        synchronized (mPackages) {
3359            checkPermissionTreeLP(name);
3360            BasePermission bp = mSettings.mPermissions.get(name);
3361            if (bp != null) {
3362                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3363                    throw new SecurityException(
3364                            "Not allowed to modify non-dynamic permission "
3365                            + name);
3366                }
3367                mSettings.mPermissions.remove(name);
3368                mSettings.writeLPr();
3369            }
3370        }
3371    }
3372
3373    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3374            BasePermission bp) {
3375        int index = pkg.requestedPermissions.indexOf(bp.name);
3376        if (index == -1) {
3377            throw new SecurityException("Package " + pkg.packageName
3378                    + " has not requested permission " + bp.name);
3379        }
3380        if (!bp.isRuntime()) {
3381            throw new SecurityException("Permission " + bp.name
3382                    + " is not a changeable permission type");
3383        }
3384    }
3385
3386    @Override
3387    public void grantRuntimePermission(String packageName, String name, final int userId) {
3388        if (!sUserManager.exists(userId)) {
3389            Log.e(TAG, "No such user:" + userId);
3390            return;
3391        }
3392
3393        mContext.enforceCallingOrSelfPermission(
3394                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3395                "grantRuntimePermission");
3396
3397        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3398                "grantRuntimePermission");
3399
3400        final int uid;
3401        final SettingBase sb;
3402
3403        synchronized (mPackages) {
3404            final PackageParser.Package pkg = mPackages.get(packageName);
3405            if (pkg == null) {
3406                throw new IllegalArgumentException("Unknown package: " + packageName);
3407            }
3408
3409            final BasePermission bp = mSettings.mPermissions.get(name);
3410            if (bp == null) {
3411                throw new IllegalArgumentException("Unknown permission: " + name);
3412            }
3413
3414            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3415
3416            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3417            sb = (SettingBase) pkg.mExtras;
3418            if (sb == null) {
3419                throw new IllegalArgumentException("Unknown package: " + packageName);
3420            }
3421
3422            final PermissionsState permissionsState = sb.getPermissionsState();
3423
3424            final int flags = permissionsState.getPermissionFlags(name, userId);
3425            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3426                throw new SecurityException("Cannot grant system fixed permission: "
3427                        + name + " for package: " + packageName);
3428            }
3429
3430            final int result = permissionsState.grantRuntimePermission(bp, userId);
3431            switch (result) {
3432                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3433                    return;
3434                }
3435
3436                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3437                    mHandler.post(new Runnable() {
3438                        @Override
3439                        public void run() {
3440                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3441                        }
3442                    });
3443                } break;
3444            }
3445
3446            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3447
3448            // Not critical if that is lost - app has to request again.
3449            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3450        }
3451
3452        // Only need to do this if user is initialized. Otherwise it's a new user
3453        // and there are no processes running as the user yet and there's no need
3454        // to make an expensive call to remount processes for the changed permissions.
3455        if (READ_EXTERNAL_STORAGE.equals(name)
3456                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3457            final long token = Binder.clearCallingIdentity();
3458            try {
3459                if (sUserManager.isInitialized(userId)) {
3460                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3461                            MountServiceInternal.class);
3462                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3463                }
3464            } finally {
3465                Binder.restoreCallingIdentity(token);
3466            }
3467        }
3468    }
3469
3470    @Override
3471    public void revokeRuntimePermission(String packageName, String name, int userId) {
3472        if (!sUserManager.exists(userId)) {
3473            Log.e(TAG, "No such user:" + userId);
3474            return;
3475        }
3476
3477        mContext.enforceCallingOrSelfPermission(
3478                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3479                "revokeRuntimePermission");
3480
3481        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3482                "revokeRuntimePermission");
3483
3484        final SettingBase sb;
3485
3486        synchronized (mPackages) {
3487            final PackageParser.Package pkg = mPackages.get(packageName);
3488            if (pkg == null) {
3489                throw new IllegalArgumentException("Unknown package: " + packageName);
3490            }
3491
3492            final BasePermission bp = mSettings.mPermissions.get(name);
3493            if (bp == null) {
3494                throw new IllegalArgumentException("Unknown permission: " + name);
3495            }
3496
3497            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3498
3499            sb = (SettingBase) pkg.mExtras;
3500            if (sb == null) {
3501                throw new IllegalArgumentException("Unknown package: " + packageName);
3502            }
3503
3504            final PermissionsState permissionsState = sb.getPermissionsState();
3505
3506            final int flags = permissionsState.getPermissionFlags(name, userId);
3507            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3508                throw new SecurityException("Cannot revoke system fixed permission: "
3509                        + name + " for package: " + packageName);
3510            }
3511
3512            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3513                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3514                return;
3515            }
3516
3517            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3518
3519            // Critical, after this call app should never have the permission.
3520            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3521        }
3522
3523        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3524    }
3525
3526    @Override
3527    public void resetRuntimePermissions() {
3528        mContext.enforceCallingOrSelfPermission(
3529                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3530                "revokeRuntimePermission");
3531
3532        int callingUid = Binder.getCallingUid();
3533        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3534            mContext.enforceCallingOrSelfPermission(
3535                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3536                    "resetRuntimePermissions");
3537        }
3538
3539        synchronized (mPackages) {
3540            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3541            for (int userId : UserManagerService.getInstance().getUserIds()) {
3542                final int packageCount = mPackages.size();
3543                for (int i = 0; i < packageCount; i++) {
3544                    PackageParser.Package pkg = mPackages.valueAt(i);
3545                    if (!(pkg.mExtras instanceof PackageSetting)) {
3546                        continue;
3547                    }
3548                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3549                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3550                }
3551            }
3552        }
3553    }
3554
3555    @Override
3556    public int getPermissionFlags(String name, String packageName, int userId) {
3557        if (!sUserManager.exists(userId)) {
3558            return 0;
3559        }
3560
3561        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3562
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3564                "getPermissionFlags");
3565
3566        synchronized (mPackages) {
3567            final PackageParser.Package pkg = mPackages.get(packageName);
3568            if (pkg == null) {
3569                throw new IllegalArgumentException("Unknown package: " + packageName);
3570            }
3571
3572            final BasePermission bp = mSettings.mPermissions.get(name);
3573            if (bp == null) {
3574                throw new IllegalArgumentException("Unknown permission: " + name);
3575            }
3576
3577            SettingBase sb = (SettingBase) pkg.mExtras;
3578            if (sb == null) {
3579                throw new IllegalArgumentException("Unknown package: " + packageName);
3580            }
3581
3582            PermissionsState permissionsState = sb.getPermissionsState();
3583            return permissionsState.getPermissionFlags(name, userId);
3584        }
3585    }
3586
3587    @Override
3588    public void updatePermissionFlags(String name, String packageName, int flagMask,
3589            int flagValues, int userId) {
3590        if (!sUserManager.exists(userId)) {
3591            return;
3592        }
3593
3594        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3595
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3597                "updatePermissionFlags");
3598
3599        // Only the system can change system fixed flags.
3600        if (getCallingUid() != Process.SYSTEM_UID) {
3601            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3602            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3603        }
3604
3605        synchronized (mPackages) {
3606            final PackageParser.Package pkg = mPackages.get(packageName);
3607            if (pkg == null) {
3608                throw new IllegalArgumentException("Unknown package: " + packageName);
3609            }
3610
3611            final BasePermission bp = mSettings.mPermissions.get(name);
3612            if (bp == null) {
3613                throw new IllegalArgumentException("Unknown permission: " + name);
3614            }
3615
3616            SettingBase sb = (SettingBase) pkg.mExtras;
3617            if (sb == null) {
3618                throw new IllegalArgumentException("Unknown package: " + packageName);
3619            }
3620
3621            PermissionsState permissionsState = sb.getPermissionsState();
3622
3623            // Only the package manager can change flags for system component permissions.
3624            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3625            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3626                return;
3627            }
3628
3629            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3630
3631            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3632                // Install and runtime permissions are stored in different places,
3633                // so figure out what permission changed and persist the change.
3634                if (permissionsState.getInstallPermissionState(name) != null) {
3635                    scheduleWriteSettingsLocked();
3636                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3637                        || hadState) {
3638                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3639                }
3640            }
3641        }
3642    }
3643
3644    /**
3645     * Update the permission flags for all packages and runtime permissions of a user in order
3646     * to allow device or profile owner to remove POLICY_FIXED.
3647     */
3648    @Override
3649    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3650        if (!sUserManager.exists(userId)) {
3651            return;
3652        }
3653
3654        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3655
3656        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3657                "updatePermissionFlagsForAllApps");
3658
3659        // Only the system can change system fixed flags.
3660        if (getCallingUid() != Process.SYSTEM_UID) {
3661            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3662            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3663        }
3664
3665        synchronized (mPackages) {
3666            boolean changed = false;
3667            final int packageCount = mPackages.size();
3668            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3669                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3670                SettingBase sb = (SettingBase) pkg.mExtras;
3671                if (sb == null) {
3672                    continue;
3673                }
3674                PermissionsState permissionsState = sb.getPermissionsState();
3675                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3676                        userId, flagMask, flagValues);
3677            }
3678            if (changed) {
3679                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3680            }
3681        }
3682    }
3683
3684    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3685        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3686                != PackageManager.PERMISSION_GRANTED
3687            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3688                != PackageManager.PERMISSION_GRANTED) {
3689            throw new SecurityException(message + " requires "
3690                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3691                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3692        }
3693    }
3694
3695    @Override
3696    public boolean shouldShowRequestPermissionRationale(String permissionName,
3697            String packageName, int userId) {
3698        if (UserHandle.getCallingUserId() != userId) {
3699            mContext.enforceCallingPermission(
3700                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3701                    "canShowRequestPermissionRationale for user " + userId);
3702        }
3703
3704        final int uid = getPackageUid(packageName, userId);
3705        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3706            return false;
3707        }
3708
3709        if (checkPermission(permissionName, packageName, userId)
3710                == PackageManager.PERMISSION_GRANTED) {
3711            return false;
3712        }
3713
3714        final int flags;
3715
3716        final long identity = Binder.clearCallingIdentity();
3717        try {
3718            flags = getPermissionFlags(permissionName,
3719                    packageName, userId);
3720        } finally {
3721            Binder.restoreCallingIdentity(identity);
3722        }
3723
3724        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3725                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3726                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3727
3728        if ((flags & fixedFlags) != 0) {
3729            return false;
3730        }
3731
3732        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3733    }
3734
3735    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3736        BasePermission bp = mSettings.mPermissions.get(permission);
3737        if (bp == null) {
3738            throw new SecurityException("Missing " + permission + " permission");
3739        }
3740
3741        SettingBase sb = (SettingBase) pkg.mExtras;
3742        PermissionsState permissionsState = sb.getPermissionsState();
3743
3744        if (permissionsState.grantInstallPermission(bp) !=
3745                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3746            scheduleWriteSettingsLocked();
3747        }
3748    }
3749
3750    @Override
3751    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3752        mContext.enforceCallingOrSelfPermission(
3753                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3754                "addOnPermissionsChangeListener");
3755
3756        synchronized (mPackages) {
3757            mOnPermissionChangeListeners.addListenerLocked(listener);
3758        }
3759    }
3760
3761    @Override
3762    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3763        synchronized (mPackages) {
3764            mOnPermissionChangeListeners.removeListenerLocked(listener);
3765        }
3766    }
3767
3768    @Override
3769    public boolean isProtectedBroadcast(String actionName) {
3770        synchronized (mPackages) {
3771            return mProtectedBroadcasts.contains(actionName);
3772        }
3773    }
3774
3775    @Override
3776    public int checkSignatures(String pkg1, String pkg2) {
3777        synchronized (mPackages) {
3778            final PackageParser.Package p1 = mPackages.get(pkg1);
3779            final PackageParser.Package p2 = mPackages.get(pkg2);
3780            if (p1 == null || p1.mExtras == null
3781                    || p2 == null || p2.mExtras == null) {
3782                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3783            }
3784            return compareSignatures(p1.mSignatures, p2.mSignatures);
3785        }
3786    }
3787
3788    @Override
3789    public int checkUidSignatures(int uid1, int uid2) {
3790        // Map to base uids.
3791        uid1 = UserHandle.getAppId(uid1);
3792        uid2 = UserHandle.getAppId(uid2);
3793        // reader
3794        synchronized (mPackages) {
3795            Signature[] s1;
3796            Signature[] s2;
3797            Object obj = mSettings.getUserIdLPr(uid1);
3798            if (obj != null) {
3799                if (obj instanceof SharedUserSetting) {
3800                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3801                } else if (obj instanceof PackageSetting) {
3802                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3803                } else {
3804                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3805                }
3806            } else {
3807                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3808            }
3809            obj = mSettings.getUserIdLPr(uid2);
3810            if (obj != null) {
3811                if (obj instanceof SharedUserSetting) {
3812                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3813                } else if (obj instanceof PackageSetting) {
3814                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3815                } else {
3816                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3817                }
3818            } else {
3819                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3820            }
3821            return compareSignatures(s1, s2);
3822        }
3823    }
3824
3825    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3826        final long identity = Binder.clearCallingIdentity();
3827        try {
3828            if (sb instanceof SharedUserSetting) {
3829                SharedUserSetting sus = (SharedUserSetting) sb;
3830                final int packageCount = sus.packages.size();
3831                for (int i = 0; i < packageCount; i++) {
3832                    PackageSetting susPs = sus.packages.valueAt(i);
3833                    if (userId == UserHandle.USER_ALL) {
3834                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3835                    } else {
3836                        final int uid = UserHandle.getUid(userId, susPs.appId);
3837                        killUid(uid, reason);
3838                    }
3839                }
3840            } else if (sb instanceof PackageSetting) {
3841                PackageSetting ps = (PackageSetting) sb;
3842                if (userId == UserHandle.USER_ALL) {
3843                    killApplication(ps.pkg.packageName, ps.appId, reason);
3844                } else {
3845                    final int uid = UserHandle.getUid(userId, ps.appId);
3846                    killUid(uid, reason);
3847                }
3848            }
3849        } finally {
3850            Binder.restoreCallingIdentity(identity);
3851        }
3852    }
3853
3854    private static void killUid(int uid, String reason) {
3855        IActivityManager am = ActivityManagerNative.getDefault();
3856        if (am != null) {
3857            try {
3858                am.killUid(uid, reason);
3859            } catch (RemoteException e) {
3860                /* ignore - same process */
3861            }
3862        }
3863    }
3864
3865    /**
3866     * Compares two sets of signatures. Returns:
3867     * <br />
3868     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3869     * <br />
3870     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3871     * <br />
3872     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3873     * <br />
3874     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3875     * <br />
3876     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3877     */
3878    static int compareSignatures(Signature[] s1, Signature[] s2) {
3879        if (s1 == null) {
3880            return s2 == null
3881                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3882                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3883        }
3884
3885        if (s2 == null) {
3886            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3887        }
3888
3889        if (s1.length != s2.length) {
3890            return PackageManager.SIGNATURE_NO_MATCH;
3891        }
3892
3893        // Since both signature sets are of size 1, we can compare without HashSets.
3894        if (s1.length == 1) {
3895            return s1[0].equals(s2[0]) ?
3896                    PackageManager.SIGNATURE_MATCH :
3897                    PackageManager.SIGNATURE_NO_MATCH;
3898        }
3899
3900        ArraySet<Signature> set1 = new ArraySet<Signature>();
3901        for (Signature sig : s1) {
3902            set1.add(sig);
3903        }
3904        ArraySet<Signature> set2 = new ArraySet<Signature>();
3905        for (Signature sig : s2) {
3906            set2.add(sig);
3907        }
3908        // Make sure s2 contains all signatures in s1.
3909        if (set1.equals(set2)) {
3910            return PackageManager.SIGNATURE_MATCH;
3911        }
3912        return PackageManager.SIGNATURE_NO_MATCH;
3913    }
3914
3915    /**
3916     * If the database version for this type of package (internal storage or
3917     * external storage) is less than the version where package signatures
3918     * were updated, return true.
3919     */
3920    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3921        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3922                DatabaseVersion.SIGNATURE_END_ENTITY))
3923                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3924                        DatabaseVersion.SIGNATURE_END_ENTITY));
3925    }
3926
3927    /**
3928     * Used for backward compatibility to make sure any packages with
3929     * certificate chains get upgraded to the new style. {@code existingSigs}
3930     * will be in the old format (since they were stored on disk from before the
3931     * system upgrade) and {@code scannedSigs} will be in the newer format.
3932     */
3933    private int compareSignaturesCompat(PackageSignatures existingSigs,
3934            PackageParser.Package scannedPkg) {
3935        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3936            return PackageManager.SIGNATURE_NO_MATCH;
3937        }
3938
3939        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3940        for (Signature sig : existingSigs.mSignatures) {
3941            existingSet.add(sig);
3942        }
3943        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3944        for (Signature sig : scannedPkg.mSignatures) {
3945            try {
3946                Signature[] chainSignatures = sig.getChainSignatures();
3947                for (Signature chainSig : chainSignatures) {
3948                    scannedCompatSet.add(chainSig);
3949                }
3950            } catch (CertificateEncodingException e) {
3951                scannedCompatSet.add(sig);
3952            }
3953        }
3954        /*
3955         * Make sure the expanded scanned set contains all signatures in the
3956         * existing one.
3957         */
3958        if (scannedCompatSet.equals(existingSet)) {
3959            // Migrate the old signatures to the new scheme.
3960            existingSigs.assignSignatures(scannedPkg.mSignatures);
3961            // The new KeySets will be re-added later in the scanning process.
3962            synchronized (mPackages) {
3963                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3964            }
3965            return PackageManager.SIGNATURE_MATCH;
3966        }
3967        return PackageManager.SIGNATURE_NO_MATCH;
3968    }
3969
3970    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3971        if (isExternal(scannedPkg)) {
3972            return mSettings.isExternalDatabaseVersionOlderThan(
3973                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3974        } else {
3975            return mSettings.isInternalDatabaseVersionOlderThan(
3976                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3977        }
3978    }
3979
3980    private int compareSignaturesRecover(PackageSignatures existingSigs,
3981            PackageParser.Package scannedPkg) {
3982        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        String msg = null;
3987        try {
3988            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3989                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3990                        + scannedPkg.packageName);
3991                return PackageManager.SIGNATURE_MATCH;
3992            }
3993        } catch (CertificateException e) {
3994            msg = e.getMessage();
3995        }
3996
3997        logCriticalInfo(Log.INFO,
3998                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3999        return PackageManager.SIGNATURE_NO_MATCH;
4000    }
4001
4002    @Override
4003    public String[] getPackagesForUid(int uid) {
4004        uid = UserHandle.getAppId(uid);
4005        // reader
4006        synchronized (mPackages) {
4007            Object obj = mSettings.getUserIdLPr(uid);
4008            if (obj instanceof SharedUserSetting) {
4009                final SharedUserSetting sus = (SharedUserSetting) obj;
4010                final int N = sus.packages.size();
4011                final String[] res = new String[N];
4012                final Iterator<PackageSetting> it = sus.packages.iterator();
4013                int i = 0;
4014                while (it.hasNext()) {
4015                    res[i++] = it.next().name;
4016                }
4017                return res;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return new String[] { ps.name };
4021            }
4022        }
4023        return null;
4024    }
4025
4026    @Override
4027    public String getNameForUid(int uid) {
4028        // reader
4029        synchronized (mPackages) {
4030            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4031            if (obj instanceof SharedUserSetting) {
4032                final SharedUserSetting sus = (SharedUserSetting) obj;
4033                return sus.name + ":" + sus.userId;
4034            } else if (obj instanceof PackageSetting) {
4035                final PackageSetting ps = (PackageSetting) obj;
4036                return ps.name;
4037            }
4038        }
4039        return null;
4040    }
4041
4042    @Override
4043    public int getUidForSharedUser(String sharedUserName) {
4044        if(sharedUserName == null) {
4045            return -1;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4050            if (suid == null) {
4051                return -1;
4052            }
4053            return suid.userId;
4054        }
4055    }
4056
4057    @Override
4058    public int getFlagsForUid(int uid) {
4059        synchronized (mPackages) {
4060            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4061            if (obj instanceof SharedUserSetting) {
4062                final SharedUserSetting sus = (SharedUserSetting) obj;
4063                return sus.pkgFlags;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return ps.pkgFlags;
4067            }
4068        }
4069        return 0;
4070    }
4071
4072    @Override
4073    public int getPrivateFlagsForUid(int uid) {
4074        synchronized (mPackages) {
4075            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4076            if (obj instanceof SharedUserSetting) {
4077                final SharedUserSetting sus = (SharedUserSetting) obj;
4078                return sus.pkgPrivateFlags;
4079            } else if (obj instanceof PackageSetting) {
4080                final PackageSetting ps = (PackageSetting) obj;
4081                return ps.pkgPrivateFlags;
4082            }
4083        }
4084        return 0;
4085    }
4086
4087    @Override
4088    public boolean isUidPrivileged(int uid) {
4089        uid = UserHandle.getAppId(uid);
4090        // reader
4091        synchronized (mPackages) {
4092            Object obj = mSettings.getUserIdLPr(uid);
4093            if (obj instanceof SharedUserSetting) {
4094                final SharedUserSetting sus = (SharedUserSetting) obj;
4095                final Iterator<PackageSetting> it = sus.packages.iterator();
4096                while (it.hasNext()) {
4097                    if (it.next().isPrivileged()) {
4098                        return true;
4099                    }
4100                }
4101            } else if (obj instanceof PackageSetting) {
4102                final PackageSetting ps = (PackageSetting) obj;
4103                return ps.isPrivileged();
4104            }
4105        }
4106        return false;
4107    }
4108
4109    @Override
4110    public String[] getAppOpPermissionPackages(String permissionName) {
4111        synchronized (mPackages) {
4112            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4113            if (pkgs == null) {
4114                return null;
4115            }
4116            return pkgs.toArray(new String[pkgs.size()]);
4117        }
4118    }
4119
4120    @Override
4121    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4122            int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4125        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4126        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4127    }
4128
4129    @Override
4130    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4131            IntentFilter filter, int match, ComponentName activity) {
4132        final int userId = UserHandle.getCallingUserId();
4133        if (DEBUG_PREFERRED) {
4134            Log.v(TAG, "setLastChosenActivity intent=" + intent
4135                + " resolvedType=" + resolvedType
4136                + " flags=" + flags
4137                + " filter=" + filter
4138                + " match=" + match
4139                + " activity=" + activity);
4140            filter.dump(new PrintStreamPrinter(System.out), "    ");
4141        }
4142        intent.setComponent(null);
4143        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4144        // Find any earlier preferred or last chosen entries and nuke them
4145        findPreferredActivity(intent, resolvedType,
4146                flags, query, 0, false, true, false, userId);
4147        // Add the new activity as the last chosen for this filter
4148        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4149                "Setting last chosen");
4150    }
4151
4152    @Override
4153    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4154        final int userId = UserHandle.getCallingUserId();
4155        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4156        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4157        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4158                false, false, false, userId);
4159    }
4160
4161    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4162            int flags, List<ResolveInfo> query, int userId) {
4163        if (query != null) {
4164            final int N = query.size();
4165            if (N == 1) {
4166                return query.get(0);
4167            } else if (N > 1) {
4168                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4169                // If there is more than one activity with the same priority,
4170                // then let the user decide between them.
4171                ResolveInfo r0 = query.get(0);
4172                ResolveInfo r1 = query.get(1);
4173                if (DEBUG_INTENT_MATCHING || debug) {
4174                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4175                            + r1.activityInfo.name + "=" + r1.priority);
4176                }
4177                // If the first activity has a higher priority, or a different
4178                // default, then it is always desireable to pick it.
4179                if (r0.priority != r1.priority
4180                        || r0.preferredOrder != r1.preferredOrder
4181                        || r0.isDefault != r1.isDefault) {
4182                    return query.get(0);
4183                }
4184                // If we have saved a preference for a preferred activity for
4185                // this Intent, use that.
4186                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4187                        flags, query, r0.priority, true, false, debug, userId);
4188                if (ri != null) {
4189                    return ri;
4190                }
4191                if (userId != 0) {
4192                    ri = new ResolveInfo(mResolveInfo);
4193                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4194                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4195                            ri.activityInfo.applicationInfo);
4196                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4197                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4198                    return ri;
4199                }
4200                return mResolveInfo;
4201            }
4202        }
4203        return null;
4204    }
4205
4206    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4207            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4208        final int N = query.size();
4209        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4210                .get(userId);
4211        // Get the list of persistent preferred activities that handle the intent
4212        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4213        List<PersistentPreferredActivity> pprefs = ppir != null
4214                ? ppir.queryIntent(intent, resolvedType,
4215                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4216                : null;
4217        if (pprefs != null && pprefs.size() > 0) {
4218            final int M = pprefs.size();
4219            for (int i=0; i<M; i++) {
4220                final PersistentPreferredActivity ppa = pprefs.get(i);
4221                if (DEBUG_PREFERRED || debug) {
4222                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4223                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4224                            + "\n  component=" + ppa.mComponent);
4225                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4226                }
4227                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4228                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4229                if (DEBUG_PREFERRED || debug) {
4230                    Slog.v(TAG, "Found persistent preferred activity:");
4231                    if (ai != null) {
4232                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4233                    } else {
4234                        Slog.v(TAG, "  null");
4235                    }
4236                }
4237                if (ai == null) {
4238                    // This previously registered persistent preferred activity
4239                    // component is no longer known. Ignore it and do NOT remove it.
4240                    continue;
4241                }
4242                for (int j=0; j<N; j++) {
4243                    final ResolveInfo ri = query.get(j);
4244                    if (!ri.activityInfo.applicationInfo.packageName
4245                            .equals(ai.applicationInfo.packageName)) {
4246                        continue;
4247                    }
4248                    if (!ri.activityInfo.name.equals(ai.name)) {
4249                        continue;
4250                    }
4251                    //  Found a persistent preference that can handle the intent.
4252                    if (DEBUG_PREFERRED || debug) {
4253                        Slog.v(TAG, "Returning persistent preferred activity: " +
4254                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4255                    }
4256                    return ri;
4257                }
4258            }
4259        }
4260        return null;
4261    }
4262
4263    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4264            List<ResolveInfo> query, int priority, boolean always,
4265            boolean removeMatches, boolean debug, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        // writer
4268        synchronized (mPackages) {
4269            if (intent.getSelector() != null) {
4270                intent = intent.getSelector();
4271            }
4272            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4273
4274            // Try to find a matching persistent preferred activity.
4275            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4276                    debug, userId);
4277
4278            // If a persistent preferred activity matched, use it.
4279            if (pri != null) {
4280                return pri;
4281            }
4282
4283            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4284            // Get the list of preferred activities that handle the intent
4285            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4286            List<PreferredActivity> prefs = pir != null
4287                    ? pir.queryIntent(intent, resolvedType,
4288                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4289                    : null;
4290            if (prefs != null && prefs.size() > 0) {
4291                boolean changed = false;
4292                try {
4293                    // First figure out how good the original match set is.
4294                    // We will only allow preferred activities that came
4295                    // from the same match quality.
4296                    int match = 0;
4297
4298                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4299
4300                    final int N = query.size();
4301                    for (int j=0; j<N; j++) {
4302                        final ResolveInfo ri = query.get(j);
4303                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4304                                + ": 0x" + Integer.toHexString(match));
4305                        if (ri.match > match) {
4306                            match = ri.match;
4307                        }
4308                    }
4309
4310                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4311                            + Integer.toHexString(match));
4312
4313                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4314                    final int M = prefs.size();
4315                    for (int i=0; i<M; i++) {
4316                        final PreferredActivity pa = prefs.get(i);
4317                        if (DEBUG_PREFERRED || debug) {
4318                            Slog.v(TAG, "Checking PreferredActivity ds="
4319                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4320                                    + "\n  component=" + pa.mPref.mComponent);
4321                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4322                        }
4323                        if (pa.mPref.mMatch != match) {
4324                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4325                                    + Integer.toHexString(pa.mPref.mMatch));
4326                            continue;
4327                        }
4328                        // If it's not an "always" type preferred activity and that's what we're
4329                        // looking for, skip it.
4330                        if (always && !pa.mPref.mAlways) {
4331                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4332                            continue;
4333                        }
4334                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4335                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4336                        if (DEBUG_PREFERRED || debug) {
4337                            Slog.v(TAG, "Found preferred activity:");
4338                            if (ai != null) {
4339                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4340                            } else {
4341                                Slog.v(TAG, "  null");
4342                            }
4343                        }
4344                        if (ai == null) {
4345                            // This previously registered preferred activity
4346                            // component is no longer known.  Most likely an update
4347                            // to the app was installed and in the new version this
4348                            // component no longer exists.  Clean it up by removing
4349                            // it from the preferred activities list, and skip it.
4350                            Slog.w(TAG, "Removing dangling preferred activity: "
4351                                    + pa.mPref.mComponent);
4352                            pir.removeFilter(pa);
4353                            changed = true;
4354                            continue;
4355                        }
4356                        for (int j=0; j<N; j++) {
4357                            final ResolveInfo ri = query.get(j);
4358                            if (!ri.activityInfo.applicationInfo.packageName
4359                                    .equals(ai.applicationInfo.packageName)) {
4360                                continue;
4361                            }
4362                            if (!ri.activityInfo.name.equals(ai.name)) {
4363                                continue;
4364                            }
4365
4366                            if (removeMatches) {
4367                                pir.removeFilter(pa);
4368                                changed = true;
4369                                if (DEBUG_PREFERRED) {
4370                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4371                                }
4372                                break;
4373                            }
4374
4375                            // Okay we found a previously set preferred or last chosen app.
4376                            // If the result set is different from when this
4377                            // was created, we need to clear it and re-ask the
4378                            // user their preference, if we're looking for an "always" type entry.
4379                            if (always && !pa.mPref.sameSet(query)) {
4380                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4381                                        + intent + " type " + resolvedType);
4382                                if (DEBUG_PREFERRED) {
4383                                    Slog.v(TAG, "Removing preferred activity since set changed "
4384                                            + pa.mPref.mComponent);
4385                                }
4386                                pir.removeFilter(pa);
4387                                // Re-add the filter as a "last chosen" entry (!always)
4388                                PreferredActivity lastChosen = new PreferredActivity(
4389                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4390                                pir.addFilter(lastChosen);
4391                                changed = true;
4392                                return null;
4393                            }
4394
4395                            // Yay! Either the set matched or we're looking for the last chosen
4396                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4397                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4398                            return ri;
4399                        }
4400                    }
4401                } finally {
4402                    if (changed) {
4403                        if (DEBUG_PREFERRED) {
4404                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4405                        }
4406                        scheduleWritePackageRestrictionsLocked(userId);
4407                    }
4408                }
4409            }
4410        }
4411        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4412        return null;
4413    }
4414
4415    /*
4416     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4417     */
4418    @Override
4419    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4420            int targetUserId) {
4421        mContext.enforceCallingOrSelfPermission(
4422                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4423        List<CrossProfileIntentFilter> matches =
4424                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4425        if (matches != null) {
4426            int size = matches.size();
4427            for (int i = 0; i < size; i++) {
4428                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4429            }
4430        }
4431        if (hasWebURI(intent)) {
4432            // cross-profile app linking works only towards the parent.
4433            final UserInfo parent = getProfileParent(sourceUserId);
4434            synchronized(mPackages) {
4435                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4436                        intent, resolvedType, 0, sourceUserId, parent.id);
4437                return xpDomainInfo != null
4438                        && xpDomainInfo.bestDomainVerificationStatus !=
4439                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4440            }
4441        }
4442        return false;
4443    }
4444
4445    private UserInfo getProfileParent(int userId) {
4446        final long identity = Binder.clearCallingIdentity();
4447        try {
4448            return sUserManager.getProfileParent(userId);
4449        } finally {
4450            Binder.restoreCallingIdentity(identity);
4451        }
4452    }
4453
4454    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4455            String resolvedType, int userId) {
4456        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4457        if (resolver != null) {
4458            return resolver.queryIntent(intent, resolvedType, false, userId);
4459        }
4460        return null;
4461    }
4462
4463    @Override
4464    public List<ResolveInfo> queryIntentActivities(Intent intent,
4465            String resolvedType, int flags, int userId) {
4466        if (!sUserManager.exists(userId)) return Collections.emptyList();
4467        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4468        ComponentName comp = intent.getComponent();
4469        if (comp == null) {
4470            if (intent.getSelector() != null) {
4471                intent = intent.getSelector();
4472                comp = intent.getComponent();
4473            }
4474        }
4475
4476        if (comp != null) {
4477            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4478            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4479            if (ai != null) {
4480                final ResolveInfo ri = new ResolveInfo();
4481                ri.activityInfo = ai;
4482                list.add(ri);
4483            }
4484            return list;
4485        }
4486
4487        // reader
4488        synchronized (mPackages) {
4489            final String pkgName = intent.getPackage();
4490            if (pkgName == null) {
4491                List<CrossProfileIntentFilter> matchingFilters =
4492                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4493                // Check for results that need to skip the current profile.
4494                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4495                        resolvedType, flags, userId);
4496                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4497                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4498                    result.add(xpResolveInfo);
4499                    return filterIfNotPrimaryUser(result, userId);
4500                }
4501
4502                // Check for results in the current profile.
4503                List<ResolveInfo> result = mActivities.queryIntent(
4504                        intent, resolvedType, flags, userId);
4505
4506                // Check for cross profile results.
4507                xpResolveInfo = queryCrossProfileIntents(
4508                        matchingFilters, intent, resolvedType, flags, userId);
4509                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4510                    result.add(xpResolveInfo);
4511                    Collections.sort(result, mResolvePrioritySorter);
4512                }
4513                result = filterIfNotPrimaryUser(result, userId);
4514                if (hasWebURI(intent)) {
4515                    CrossProfileDomainInfo xpDomainInfo = null;
4516                    final UserInfo parent = getProfileParent(userId);
4517                    if (parent != null) {
4518                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4519                                flags, userId, parent.id);
4520                    }
4521                    if (xpDomainInfo != null) {
4522                        if (xpResolveInfo != null) {
4523                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4524                            // in the result.
4525                            result.remove(xpResolveInfo);
4526                        }
4527                        if (result.size() == 0) {
4528                            result.add(xpDomainInfo.resolveInfo);
4529                            return result;
4530                        }
4531                    } else if (result.size() <= 1) {
4532                        return result;
4533                    }
4534                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4535                            xpDomainInfo, userId);
4536                    Collections.sort(result, mResolvePrioritySorter);
4537                }
4538                return result;
4539            }
4540            final PackageParser.Package pkg = mPackages.get(pkgName);
4541            if (pkg != null) {
4542                return filterIfNotPrimaryUser(
4543                        mActivities.queryIntentForPackage(
4544                                intent, resolvedType, flags, pkg.activities, userId),
4545                        userId);
4546            }
4547            return new ArrayList<ResolveInfo>();
4548        }
4549    }
4550
4551    private static class CrossProfileDomainInfo {
4552        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4553        ResolveInfo resolveInfo;
4554        /* Best domain verification status of the activities found in the other profile */
4555        int bestDomainVerificationStatus;
4556    }
4557
4558    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4559            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4560        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4561                sourceUserId)) {
4562            return null;
4563        }
4564        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4565                resolvedType, flags, parentUserId);
4566
4567        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4568            return null;
4569        }
4570        CrossProfileDomainInfo result = null;
4571        int size = resultTargetUser.size();
4572        for (int i = 0; i < size; i++) {
4573            ResolveInfo riTargetUser = resultTargetUser.get(i);
4574            // Intent filter verification is only for filters that specify a host. So don't return
4575            // those that handle all web uris.
4576            if (riTargetUser.handleAllWebDataURI) {
4577                continue;
4578            }
4579            String packageName = riTargetUser.activityInfo.packageName;
4580            PackageSetting ps = mSettings.mPackages.get(packageName);
4581            if (ps == null) {
4582                continue;
4583            }
4584            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4585            int status = (int)(verificationState >> 32);
4586            if (result == null) {
4587                result = new CrossProfileDomainInfo();
4588                result.resolveInfo =
4589                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4590                result.bestDomainVerificationStatus = status;
4591            } else {
4592                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4593                        result.bestDomainVerificationStatus);
4594            }
4595        }
4596        return result;
4597    }
4598
4599    /**
4600     * Verification statuses are ordered from the worse to the best, except for
4601     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4602     */
4603    private int bestDomainVerificationStatus(int status1, int status2) {
4604        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4605            return status2;
4606        }
4607        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4608            return status1;
4609        }
4610        return (int) MathUtils.max(status1, status2);
4611    }
4612
4613    private boolean isUserEnabled(int userId) {
4614        long callingId = Binder.clearCallingIdentity();
4615        try {
4616            UserInfo userInfo = sUserManager.getUserInfo(userId);
4617            return userInfo != null && userInfo.isEnabled();
4618        } finally {
4619            Binder.restoreCallingIdentity(callingId);
4620        }
4621    }
4622
4623    /**
4624     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4625     *
4626     * @return filtered list
4627     */
4628    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4629        if (userId == UserHandle.USER_OWNER) {
4630            return resolveInfos;
4631        }
4632        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4633            ResolveInfo info = resolveInfos.get(i);
4634            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4635                resolveInfos.remove(i);
4636            }
4637        }
4638        return resolveInfos;
4639    }
4640
4641    private static boolean hasWebURI(Intent intent) {
4642        if (intent.getData() == null) {
4643            return false;
4644        }
4645        final String scheme = intent.getScheme();
4646        if (TextUtils.isEmpty(scheme)) {
4647            return false;
4648        }
4649        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4650    }
4651
4652    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4653            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4654            int userId) {
4655        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4656
4657        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4658            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4659                    candidates.size());
4660        }
4661
4662        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4663        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4664        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4665        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4666        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4667
4668        synchronized (mPackages) {
4669            final int count = candidates.size();
4670            // First, try to use linked apps. Partition the candidates into four lists:
4671            // one for the final results, one for the "do not use ever", one for "undefined status"
4672            // and finally one for "browser app type".
4673            for (int n=0; n<count; n++) {
4674                ResolveInfo info = candidates.get(n);
4675                String packageName = info.activityInfo.packageName;
4676                PackageSetting ps = mSettings.mPackages.get(packageName);
4677                if (ps != null) {
4678                    // Add to the special match all list (Browser use case)
4679                    if (info.handleAllWebDataURI) {
4680                        matchAllList.add(info);
4681                        continue;
4682                    }
4683                    // Try to get the status from User settings first
4684                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4685                    int status = (int)(packedStatus >> 32);
4686                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4687                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4688                        if (DEBUG_DOMAIN_VERIFICATION) {
4689                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4690                                    + " : linkgen=" + linkGeneration);
4691                        }
4692                        // Use link-enabled generation as preferredOrder, i.e.
4693                        // prefer newly-enabled over earlier-enabled.
4694                        info.preferredOrder = linkGeneration;
4695                        alwaysList.add(info);
4696                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4697                        if (DEBUG_DOMAIN_VERIFICATION) {
4698                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4699                        }
4700                        neverList.add(info);
4701                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4702                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4703                        if (DEBUG_DOMAIN_VERIFICATION) {
4704                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4705                        }
4706                        undefinedList.add(info);
4707                    }
4708                }
4709            }
4710            // First try to add the "always" resolution(s) for the current user, if any
4711            if (alwaysList.size() > 0) {
4712                result.addAll(alwaysList);
4713            // if there is an "always" for the parent user, add it.
4714            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4715                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4716                result.add(xpDomainInfo.resolveInfo);
4717            } else {
4718                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4719                result.addAll(undefinedList);
4720                if (xpDomainInfo != null && (
4721                        xpDomainInfo.bestDomainVerificationStatus
4722                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4723                        || xpDomainInfo.bestDomainVerificationStatus
4724                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4725                    result.add(xpDomainInfo.resolveInfo);
4726                }
4727                // Also add Browsers (all of them or only the default one)
4728                if ((matchFlags & MATCH_ALL) != 0) {
4729                    result.addAll(matchAllList);
4730                } else {
4731                    // Browser/generic handling case.  If there's a default browser, go straight
4732                    // to that (but only if there is no other higher-priority match).
4733                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4734                            UserHandle.myUserId());
4735                    int maxMatchPrio = 0;
4736                    ResolveInfo defaultBrowserMatch = null;
4737                    final int numCandidates = matchAllList.size();
4738                    for (int n = 0; n < numCandidates; n++) {
4739                        ResolveInfo info = matchAllList.get(n);
4740                        // track the highest overall match priority...
4741                        if (info.priority > maxMatchPrio) {
4742                            maxMatchPrio = info.priority;
4743                        }
4744                        // ...and the highest-priority default browser match
4745                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4746                            if (defaultBrowserMatch == null
4747                                    || (defaultBrowserMatch.priority < info.priority)) {
4748                                if (debug) {
4749                                    Slog.v(TAG, "Considering default browser match " + info);
4750                                }
4751                                defaultBrowserMatch = info;
4752                            }
4753                        }
4754                    }
4755                    if (defaultBrowserMatch != null
4756                            && defaultBrowserMatch.priority >= maxMatchPrio
4757                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4758                    {
4759                        if (debug) {
4760                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4761                        }
4762                        result.add(defaultBrowserMatch);
4763                    } else {
4764                        result.addAll(matchAllList);
4765                    }
4766                }
4767
4768                // If there is nothing selected, add all candidates and remove the ones that the user
4769                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4770                if (result.size() == 0) {
4771                    result.addAll(candidates);
4772                    result.removeAll(neverList);
4773                }
4774            }
4775        }
4776        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4777            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4778                    result.size());
4779            for (ResolveInfo info : result) {
4780                Slog.v(TAG, "  + " + info.activityInfo);
4781            }
4782        }
4783        return result;
4784    }
4785
4786    // Returns a packed value as a long:
4787    //
4788    // high 'int'-sized word: link status: undefined/ask/never/always.
4789    // low 'int'-sized word: relative priority among 'always' results.
4790    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4791        long result = ps.getDomainVerificationStatusForUser(userId);
4792        // if none available, get the master status
4793        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4794            if (ps.getIntentFilterVerificationInfo() != null) {
4795                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4796            }
4797        }
4798        return result;
4799    }
4800
4801    private ResolveInfo querySkipCurrentProfileIntents(
4802            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4803            int flags, int sourceUserId) {
4804        if (matchingFilters != null) {
4805            int size = matchingFilters.size();
4806            for (int i = 0; i < size; i ++) {
4807                CrossProfileIntentFilter filter = matchingFilters.get(i);
4808                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4809                    // Checking if there are activities in the target user that can handle the
4810                    // intent.
4811                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4812                            flags, sourceUserId);
4813                    if (resolveInfo != null) {
4814                        return resolveInfo;
4815                    }
4816                }
4817            }
4818        }
4819        return null;
4820    }
4821
4822    // Return matching ResolveInfo if any for skip current profile intent filters.
4823    private ResolveInfo queryCrossProfileIntents(
4824            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4825            int flags, int sourceUserId) {
4826        if (matchingFilters != null) {
4827            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4828            // match the same intent. For performance reasons, it is better not to
4829            // run queryIntent twice for the same userId
4830            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4831            int size = matchingFilters.size();
4832            for (int i = 0; i < size; i++) {
4833                CrossProfileIntentFilter filter = matchingFilters.get(i);
4834                int targetUserId = filter.getTargetUserId();
4835                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4836                        && !alreadyTriedUserIds.get(targetUserId)) {
4837                    // Checking if there are activities in the target user that can handle the
4838                    // intent.
4839                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4840                            flags, sourceUserId);
4841                    if (resolveInfo != null) return resolveInfo;
4842                    alreadyTriedUserIds.put(targetUserId, true);
4843                }
4844            }
4845        }
4846        return null;
4847    }
4848
4849    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4850            String resolvedType, int flags, int sourceUserId) {
4851        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4852                resolvedType, flags, filter.getTargetUserId());
4853        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4854            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4855        }
4856        return null;
4857    }
4858
4859    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4860            int sourceUserId, int targetUserId) {
4861        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4862        String className;
4863        if (targetUserId == UserHandle.USER_OWNER) {
4864            className = FORWARD_INTENT_TO_USER_OWNER;
4865        } else {
4866            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4867        }
4868        ComponentName forwardingActivityComponentName = new ComponentName(
4869                mAndroidApplication.packageName, className);
4870        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4871                sourceUserId);
4872        if (targetUserId == UserHandle.USER_OWNER) {
4873            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4874            forwardingResolveInfo.noResourceId = true;
4875        }
4876        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4877        forwardingResolveInfo.priority = 0;
4878        forwardingResolveInfo.preferredOrder = 0;
4879        forwardingResolveInfo.match = 0;
4880        forwardingResolveInfo.isDefault = true;
4881        forwardingResolveInfo.filter = filter;
4882        forwardingResolveInfo.targetUserId = targetUserId;
4883        return forwardingResolveInfo;
4884    }
4885
4886    @Override
4887    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4888            Intent[] specifics, String[] specificTypes, Intent intent,
4889            String resolvedType, int flags, int userId) {
4890        if (!sUserManager.exists(userId)) return Collections.emptyList();
4891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4892                false, "query intent activity options");
4893        final String resultsAction = intent.getAction();
4894
4895        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4896                | PackageManager.GET_RESOLVED_FILTER, userId);
4897
4898        if (DEBUG_INTENT_MATCHING) {
4899            Log.v(TAG, "Query " + intent + ": " + results);
4900        }
4901
4902        int specificsPos = 0;
4903        int N;
4904
4905        // todo: note that the algorithm used here is O(N^2).  This
4906        // isn't a problem in our current environment, but if we start running
4907        // into situations where we have more than 5 or 10 matches then this
4908        // should probably be changed to something smarter...
4909
4910        // First we go through and resolve each of the specific items
4911        // that were supplied, taking care of removing any corresponding
4912        // duplicate items in the generic resolve list.
4913        if (specifics != null) {
4914            for (int i=0; i<specifics.length; i++) {
4915                final Intent sintent = specifics[i];
4916                if (sintent == null) {
4917                    continue;
4918                }
4919
4920                if (DEBUG_INTENT_MATCHING) {
4921                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4922                }
4923
4924                String action = sintent.getAction();
4925                if (resultsAction != null && resultsAction.equals(action)) {
4926                    // If this action was explicitly requested, then don't
4927                    // remove things that have it.
4928                    action = null;
4929                }
4930
4931                ResolveInfo ri = null;
4932                ActivityInfo ai = null;
4933
4934                ComponentName comp = sintent.getComponent();
4935                if (comp == null) {
4936                    ri = resolveIntent(
4937                        sintent,
4938                        specificTypes != null ? specificTypes[i] : null,
4939                            flags, userId);
4940                    if (ri == null) {
4941                        continue;
4942                    }
4943                    if (ri == mResolveInfo) {
4944                        // ACK!  Must do something better with this.
4945                    }
4946                    ai = ri.activityInfo;
4947                    comp = new ComponentName(ai.applicationInfo.packageName,
4948                            ai.name);
4949                } else {
4950                    ai = getActivityInfo(comp, flags, userId);
4951                    if (ai == null) {
4952                        continue;
4953                    }
4954                }
4955
4956                // Look for any generic query activities that are duplicates
4957                // of this specific one, and remove them from the results.
4958                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4959                N = results.size();
4960                int j;
4961                for (j=specificsPos; j<N; j++) {
4962                    ResolveInfo sri = results.get(j);
4963                    if ((sri.activityInfo.name.equals(comp.getClassName())
4964                            && sri.activityInfo.applicationInfo.packageName.equals(
4965                                    comp.getPackageName()))
4966                        || (action != null && sri.filter.matchAction(action))) {
4967                        results.remove(j);
4968                        if (DEBUG_INTENT_MATCHING) Log.v(
4969                            TAG, "Removing duplicate item from " + j
4970                            + " due to specific " + specificsPos);
4971                        if (ri == null) {
4972                            ri = sri;
4973                        }
4974                        j--;
4975                        N--;
4976                    }
4977                }
4978
4979                // Add this specific item to its proper place.
4980                if (ri == null) {
4981                    ri = new ResolveInfo();
4982                    ri.activityInfo = ai;
4983                }
4984                results.add(specificsPos, ri);
4985                ri.specificIndex = i;
4986                specificsPos++;
4987            }
4988        }
4989
4990        // Now we go through the remaining generic results and remove any
4991        // duplicate actions that are found here.
4992        N = results.size();
4993        for (int i=specificsPos; i<N-1; i++) {
4994            final ResolveInfo rii = results.get(i);
4995            if (rii.filter == null) {
4996                continue;
4997            }
4998
4999            // Iterate over all of the actions of this result's intent
5000            // filter...  typically this should be just one.
5001            final Iterator<String> it = rii.filter.actionsIterator();
5002            if (it == null) {
5003                continue;
5004            }
5005            while (it.hasNext()) {
5006                final String action = it.next();
5007                if (resultsAction != null && resultsAction.equals(action)) {
5008                    // If this action was explicitly requested, then don't
5009                    // remove things that have it.
5010                    continue;
5011                }
5012                for (int j=i+1; j<N; j++) {
5013                    final ResolveInfo rij = results.get(j);
5014                    if (rij.filter != null && rij.filter.hasAction(action)) {
5015                        results.remove(j);
5016                        if (DEBUG_INTENT_MATCHING) Log.v(
5017                            TAG, "Removing duplicate item from " + j
5018                            + " due to action " + action + " at " + i);
5019                        j--;
5020                        N--;
5021                    }
5022                }
5023            }
5024
5025            // If the caller didn't request filter information, drop it now
5026            // so we don't have to marshall/unmarshall it.
5027            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5028                rii.filter = null;
5029            }
5030        }
5031
5032        // Filter out the caller activity if so requested.
5033        if (caller != null) {
5034            N = results.size();
5035            for (int i=0; i<N; i++) {
5036                ActivityInfo ainfo = results.get(i).activityInfo;
5037                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5038                        && caller.getClassName().equals(ainfo.name)) {
5039                    results.remove(i);
5040                    break;
5041                }
5042            }
5043        }
5044
5045        // If the caller didn't request filter information,
5046        // drop them now so we don't have to
5047        // marshall/unmarshall it.
5048        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5049            N = results.size();
5050            for (int i=0; i<N; i++) {
5051                results.get(i).filter = null;
5052            }
5053        }
5054
5055        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5056        return results;
5057    }
5058
5059    @Override
5060    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5061            int userId) {
5062        if (!sUserManager.exists(userId)) return Collections.emptyList();
5063        ComponentName comp = intent.getComponent();
5064        if (comp == null) {
5065            if (intent.getSelector() != null) {
5066                intent = intent.getSelector();
5067                comp = intent.getComponent();
5068            }
5069        }
5070        if (comp != null) {
5071            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5072            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5073            if (ai != null) {
5074                ResolveInfo ri = new ResolveInfo();
5075                ri.activityInfo = ai;
5076                list.add(ri);
5077            }
5078            return list;
5079        }
5080
5081        // reader
5082        synchronized (mPackages) {
5083            String pkgName = intent.getPackage();
5084            if (pkgName == null) {
5085                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5086            }
5087            final PackageParser.Package pkg = mPackages.get(pkgName);
5088            if (pkg != null) {
5089                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5090                        userId);
5091            }
5092            return null;
5093        }
5094    }
5095
5096    @Override
5097    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5098        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5099        if (!sUserManager.exists(userId)) return null;
5100        if (query != null) {
5101            if (query.size() >= 1) {
5102                // If there is more than one service with the same priority,
5103                // just arbitrarily pick the first one.
5104                return query.get(0);
5105            }
5106        }
5107        return null;
5108    }
5109
5110    @Override
5111    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5112            int userId) {
5113        if (!sUserManager.exists(userId)) return Collections.emptyList();
5114        ComponentName comp = intent.getComponent();
5115        if (comp == null) {
5116            if (intent.getSelector() != null) {
5117                intent = intent.getSelector();
5118                comp = intent.getComponent();
5119            }
5120        }
5121        if (comp != null) {
5122            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5123            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5124            if (si != null) {
5125                final ResolveInfo ri = new ResolveInfo();
5126                ri.serviceInfo = si;
5127                list.add(ri);
5128            }
5129            return list;
5130        }
5131
5132        // reader
5133        synchronized (mPackages) {
5134            String pkgName = intent.getPackage();
5135            if (pkgName == null) {
5136                return mServices.queryIntent(intent, resolvedType, flags, userId);
5137            }
5138            final PackageParser.Package pkg = mPackages.get(pkgName);
5139            if (pkg != null) {
5140                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5141                        userId);
5142            }
5143            return null;
5144        }
5145    }
5146
5147    @Override
5148    public List<ResolveInfo> queryIntentContentProviders(
5149            Intent intent, String resolvedType, int flags, int userId) {
5150        if (!sUserManager.exists(userId)) return Collections.emptyList();
5151        ComponentName comp = intent.getComponent();
5152        if (comp == null) {
5153            if (intent.getSelector() != null) {
5154                intent = intent.getSelector();
5155                comp = intent.getComponent();
5156            }
5157        }
5158        if (comp != null) {
5159            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5160            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5161            if (pi != null) {
5162                final ResolveInfo ri = new ResolveInfo();
5163                ri.providerInfo = pi;
5164                list.add(ri);
5165            }
5166            return list;
5167        }
5168
5169        // reader
5170        synchronized (mPackages) {
5171            String pkgName = intent.getPackage();
5172            if (pkgName == null) {
5173                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5174            }
5175            final PackageParser.Package pkg = mPackages.get(pkgName);
5176            if (pkg != null) {
5177                return mProviders.queryIntentForPackage(
5178                        intent, resolvedType, flags, pkg.providers, userId);
5179            }
5180            return null;
5181        }
5182    }
5183
5184    @Override
5185    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5186        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5187
5188        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5189
5190        // writer
5191        synchronized (mPackages) {
5192            ArrayList<PackageInfo> list;
5193            if (listUninstalled) {
5194                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5195                for (PackageSetting ps : mSettings.mPackages.values()) {
5196                    PackageInfo pi;
5197                    if (ps.pkg != null) {
5198                        pi = generatePackageInfo(ps.pkg, flags, userId);
5199                    } else {
5200                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5201                    }
5202                    if (pi != null) {
5203                        list.add(pi);
5204                    }
5205                }
5206            } else {
5207                list = new ArrayList<PackageInfo>(mPackages.size());
5208                for (PackageParser.Package p : mPackages.values()) {
5209                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5210                    if (pi != null) {
5211                        list.add(pi);
5212                    }
5213                }
5214            }
5215
5216            return new ParceledListSlice<PackageInfo>(list);
5217        }
5218    }
5219
5220    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5221            String[] permissions, boolean[] tmp, int flags, int userId) {
5222        int numMatch = 0;
5223        final PermissionsState permissionsState = ps.getPermissionsState();
5224        for (int i=0; i<permissions.length; i++) {
5225            final String permission = permissions[i];
5226            if (permissionsState.hasPermission(permission, userId)) {
5227                tmp[i] = true;
5228                numMatch++;
5229            } else {
5230                tmp[i] = false;
5231            }
5232        }
5233        if (numMatch == 0) {
5234            return;
5235        }
5236        PackageInfo pi;
5237        if (ps.pkg != null) {
5238            pi = generatePackageInfo(ps.pkg, flags, userId);
5239        } else {
5240            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5241        }
5242        // The above might return null in cases of uninstalled apps or install-state
5243        // skew across users/profiles.
5244        if (pi != null) {
5245            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5246                if (numMatch == permissions.length) {
5247                    pi.requestedPermissions = permissions;
5248                } else {
5249                    pi.requestedPermissions = new String[numMatch];
5250                    numMatch = 0;
5251                    for (int i=0; i<permissions.length; i++) {
5252                        if (tmp[i]) {
5253                            pi.requestedPermissions[numMatch] = permissions[i];
5254                            numMatch++;
5255                        }
5256                    }
5257                }
5258            }
5259            list.add(pi);
5260        }
5261    }
5262
5263    @Override
5264    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5265            String[] permissions, int flags, int userId) {
5266        if (!sUserManager.exists(userId)) return null;
5267        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5268
5269        // writer
5270        synchronized (mPackages) {
5271            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5272            boolean[] tmpBools = new boolean[permissions.length];
5273            if (listUninstalled) {
5274                for (PackageSetting ps : mSettings.mPackages.values()) {
5275                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5276                }
5277            } else {
5278                for (PackageParser.Package pkg : mPackages.values()) {
5279                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5280                    if (ps != null) {
5281                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5282                                userId);
5283                    }
5284                }
5285            }
5286
5287            return new ParceledListSlice<PackageInfo>(list);
5288        }
5289    }
5290
5291    @Override
5292    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5293        if (!sUserManager.exists(userId)) return null;
5294        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5295
5296        // writer
5297        synchronized (mPackages) {
5298            ArrayList<ApplicationInfo> list;
5299            if (listUninstalled) {
5300                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5301                for (PackageSetting ps : mSettings.mPackages.values()) {
5302                    ApplicationInfo ai;
5303                    if (ps.pkg != null) {
5304                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5305                                ps.readUserState(userId), userId);
5306                    } else {
5307                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5308                    }
5309                    if (ai != null) {
5310                        list.add(ai);
5311                    }
5312                }
5313            } else {
5314                list = new ArrayList<ApplicationInfo>(mPackages.size());
5315                for (PackageParser.Package p : mPackages.values()) {
5316                    if (p.mExtras != null) {
5317                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5318                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5319                        if (ai != null) {
5320                            list.add(ai);
5321                        }
5322                    }
5323                }
5324            }
5325
5326            return new ParceledListSlice<ApplicationInfo>(list);
5327        }
5328    }
5329
5330    public List<ApplicationInfo> getPersistentApplications(int flags) {
5331        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5332
5333        // reader
5334        synchronized (mPackages) {
5335            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5336            final int userId = UserHandle.getCallingUserId();
5337            while (i.hasNext()) {
5338                final PackageParser.Package p = i.next();
5339                if (p.applicationInfo != null
5340                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5341                        && (!mSafeMode || isSystemApp(p))) {
5342                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5343                    if (ps != null) {
5344                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5345                                ps.readUserState(userId), userId);
5346                        if (ai != null) {
5347                            finalList.add(ai);
5348                        }
5349                    }
5350                }
5351            }
5352        }
5353
5354        return finalList;
5355    }
5356
5357    @Override
5358    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5359        if (!sUserManager.exists(userId)) return null;
5360        // reader
5361        synchronized (mPackages) {
5362            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5363            PackageSetting ps = provider != null
5364                    ? mSettings.mPackages.get(provider.owner.packageName)
5365                    : null;
5366            return ps != null
5367                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5368                    && (!mSafeMode || (provider.info.applicationInfo.flags
5369                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5370                    ? PackageParser.generateProviderInfo(provider, flags,
5371                            ps.readUserState(userId), userId)
5372                    : null;
5373        }
5374    }
5375
5376    /**
5377     * @deprecated
5378     */
5379    @Deprecated
5380    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5381        // reader
5382        synchronized (mPackages) {
5383            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5384                    .entrySet().iterator();
5385            final int userId = UserHandle.getCallingUserId();
5386            while (i.hasNext()) {
5387                Map.Entry<String, PackageParser.Provider> entry = i.next();
5388                PackageParser.Provider p = entry.getValue();
5389                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5390
5391                if (ps != null && p.syncable
5392                        && (!mSafeMode || (p.info.applicationInfo.flags
5393                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5394                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5395                            ps.readUserState(userId), userId);
5396                    if (info != null) {
5397                        outNames.add(entry.getKey());
5398                        outInfo.add(info);
5399                    }
5400                }
5401            }
5402        }
5403    }
5404
5405    @Override
5406    public List<ProviderInfo> queryContentProviders(String processName,
5407            int uid, int flags) {
5408        ArrayList<ProviderInfo> finalList = null;
5409        // reader
5410        synchronized (mPackages) {
5411            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5412            final int userId = processName != null ?
5413                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5414            while (i.hasNext()) {
5415                final PackageParser.Provider p = i.next();
5416                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5417                if (ps != null && p.info.authority != null
5418                        && (processName == null
5419                                || (p.info.processName.equals(processName)
5420                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5421                        && mSettings.isEnabledLPr(p.info, flags, userId)
5422                        && (!mSafeMode
5423                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5424                    if (finalList == null) {
5425                        finalList = new ArrayList<ProviderInfo>(3);
5426                    }
5427                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5428                            ps.readUserState(userId), userId);
5429                    if (info != null) {
5430                        finalList.add(info);
5431                    }
5432                }
5433            }
5434        }
5435
5436        if (finalList != null) {
5437            Collections.sort(finalList, mProviderInitOrderSorter);
5438        }
5439
5440        return finalList;
5441    }
5442
5443    @Override
5444    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5445            int flags) {
5446        // reader
5447        synchronized (mPackages) {
5448            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5449            return PackageParser.generateInstrumentationInfo(i, flags);
5450        }
5451    }
5452
5453    @Override
5454    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5455            int flags) {
5456        ArrayList<InstrumentationInfo> finalList =
5457            new ArrayList<InstrumentationInfo>();
5458
5459        // reader
5460        synchronized (mPackages) {
5461            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5462            while (i.hasNext()) {
5463                final PackageParser.Instrumentation p = i.next();
5464                if (targetPackage == null
5465                        || targetPackage.equals(p.info.targetPackage)) {
5466                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5467                            flags);
5468                    if (ii != null) {
5469                        finalList.add(ii);
5470                    }
5471                }
5472            }
5473        }
5474
5475        return finalList;
5476    }
5477
5478    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5479        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5480        if (overlays == null) {
5481            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5482            return;
5483        }
5484        for (PackageParser.Package opkg : overlays.values()) {
5485            // Not much to do if idmap fails: we already logged the error
5486            // and we certainly don't want to abort installation of pkg simply
5487            // because an overlay didn't fit properly. For these reasons,
5488            // ignore the return value of createIdmapForPackagePairLI.
5489            createIdmapForPackagePairLI(pkg, opkg);
5490        }
5491    }
5492
5493    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5494            PackageParser.Package opkg) {
5495        if (!opkg.mTrustedOverlay) {
5496            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5497                    opkg.baseCodePath + ": overlay not trusted");
5498            return false;
5499        }
5500        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5501        if (overlaySet == null) {
5502            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5503                    opkg.baseCodePath + " but target package has no known overlays");
5504            return false;
5505        }
5506        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5507        // TODO: generate idmap for split APKs
5508        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5509            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5510                    + opkg.baseCodePath);
5511            return false;
5512        }
5513        PackageParser.Package[] overlayArray =
5514            overlaySet.values().toArray(new PackageParser.Package[0]);
5515        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5516            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5517                return p1.mOverlayPriority - p2.mOverlayPriority;
5518            }
5519        };
5520        Arrays.sort(overlayArray, cmp);
5521
5522        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5523        int i = 0;
5524        for (PackageParser.Package p : overlayArray) {
5525            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5526        }
5527        return true;
5528    }
5529
5530    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5531        final File[] files = dir.listFiles();
5532        if (ArrayUtils.isEmpty(files)) {
5533            Log.d(TAG, "No files in app dir " + dir);
5534            return;
5535        }
5536
5537        if (DEBUG_PACKAGE_SCANNING) {
5538            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5539                    + " flags=0x" + Integer.toHexString(parseFlags));
5540        }
5541
5542        for (File file : files) {
5543            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5544                    && !PackageInstallerService.isStageName(file.getName());
5545            if (!isPackage) {
5546                // Ignore entries which are not packages
5547                continue;
5548            }
5549            try {
5550                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5551                        scanFlags, currentTime, null);
5552            } catch (PackageManagerException e) {
5553                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5554
5555                // Delete invalid userdata apps
5556                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5557                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5558                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5559                    if (file.isDirectory()) {
5560                        mInstaller.rmPackageDir(file.getAbsolutePath());
5561                    } else {
5562                        file.delete();
5563                    }
5564                }
5565            }
5566        }
5567    }
5568
5569    private static File getSettingsProblemFile() {
5570        File dataDir = Environment.getDataDirectory();
5571        File systemDir = new File(dataDir, "system");
5572        File fname = new File(systemDir, "uiderrors.txt");
5573        return fname;
5574    }
5575
5576    static void reportSettingsProblem(int priority, String msg) {
5577        logCriticalInfo(priority, msg);
5578    }
5579
5580    static void logCriticalInfo(int priority, String msg) {
5581        Slog.println(priority, TAG, msg);
5582        EventLogTags.writePmCriticalInfo(msg);
5583        try {
5584            File fname = getSettingsProblemFile();
5585            FileOutputStream out = new FileOutputStream(fname, true);
5586            PrintWriter pw = new FastPrintWriter(out);
5587            SimpleDateFormat formatter = new SimpleDateFormat();
5588            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5589            pw.println(dateString + ": " + msg);
5590            pw.close();
5591            FileUtils.setPermissions(
5592                    fname.toString(),
5593                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5594                    -1, -1);
5595        } catch (java.io.IOException e) {
5596        }
5597    }
5598
5599    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5600            PackageParser.Package pkg, File srcFile, int parseFlags)
5601            throws PackageManagerException {
5602        if (ps != null
5603                && ps.codePath.equals(srcFile)
5604                && ps.timeStamp == srcFile.lastModified()
5605                && !isCompatSignatureUpdateNeeded(pkg)
5606                && !isRecoverSignatureUpdateNeeded(pkg)) {
5607            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5608            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5609            ArraySet<PublicKey> signingKs;
5610            synchronized (mPackages) {
5611                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5612            }
5613            if (ps.signatures.mSignatures != null
5614                    && ps.signatures.mSignatures.length != 0
5615                    && signingKs != null) {
5616                // Optimization: reuse the existing cached certificates
5617                // if the package appears to be unchanged.
5618                pkg.mSignatures = ps.signatures.mSignatures;
5619                pkg.mSigningKeys = signingKs;
5620                return;
5621            }
5622
5623            Slog.w(TAG, "PackageSetting for " + ps.name
5624                    + " is missing signatures.  Collecting certs again to recover them.");
5625        } else {
5626            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5627        }
5628
5629        try {
5630            pp.collectCertificates(pkg, parseFlags);
5631            pp.collectManifestDigest(pkg);
5632        } catch (PackageParserException e) {
5633            throw PackageManagerException.from(e);
5634        }
5635    }
5636
5637    /*
5638     *  Scan a package and return the newly parsed package.
5639     *  Returns null in case of errors and the error code is stored in mLastScanError
5640     */
5641    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5642            long currentTime, UserHandle user) throws PackageManagerException {
5643        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5644        parseFlags |= mDefParseFlags;
5645        PackageParser pp = new PackageParser();
5646        pp.setSeparateProcesses(mSeparateProcesses);
5647        pp.setOnlyCoreApps(mOnlyCore);
5648        pp.setDisplayMetrics(mMetrics);
5649
5650        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5651            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5652        }
5653
5654        final PackageParser.Package pkg;
5655        try {
5656            pkg = pp.parsePackage(scanFile, parseFlags);
5657        } catch (PackageParserException e) {
5658            throw PackageManagerException.from(e);
5659        }
5660
5661        PackageSetting ps = null;
5662        PackageSetting updatedPkg;
5663        // reader
5664        synchronized (mPackages) {
5665            // Look to see if we already know about this package.
5666            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5667            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5668                // This package has been renamed to its original name.  Let's
5669                // use that.
5670                ps = mSettings.peekPackageLPr(oldName);
5671            }
5672            // If there was no original package, see one for the real package name.
5673            if (ps == null) {
5674                ps = mSettings.peekPackageLPr(pkg.packageName);
5675            }
5676            // Check to see if this package could be hiding/updating a system
5677            // package.  Must look for it either under the original or real
5678            // package name depending on our state.
5679            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5680            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5681        }
5682        boolean updatedPkgBetter = false;
5683        // First check if this is a system package that may involve an update
5684        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5685            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5686            // it needs to drop FLAG_PRIVILEGED.
5687            if (locationIsPrivileged(scanFile)) {
5688                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5689            } else {
5690                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5691            }
5692
5693            if (ps != null && !ps.codePath.equals(scanFile)) {
5694                // The path has changed from what was last scanned...  check the
5695                // version of the new path against what we have stored to determine
5696                // what to do.
5697                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5698                if (pkg.mVersionCode <= ps.versionCode) {
5699                    // The system package has been updated and the code path does not match
5700                    // Ignore entry. Skip it.
5701                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5702                            + " ignored: updated version " + ps.versionCode
5703                            + " better than this " + pkg.mVersionCode);
5704                    if (!updatedPkg.codePath.equals(scanFile)) {
5705                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5706                                + ps.name + " changing from " + updatedPkg.codePathString
5707                                + " to " + scanFile);
5708                        updatedPkg.codePath = scanFile;
5709                        updatedPkg.codePathString = scanFile.toString();
5710                        updatedPkg.resourcePath = scanFile;
5711                        updatedPkg.resourcePathString = scanFile.toString();
5712                    }
5713                    updatedPkg.pkg = pkg;
5714                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5715                            "Package " + ps.name + " at " + scanFile
5716                                    + " ignored: updated version " + ps.versionCode
5717                                    + " better than this " + pkg.mVersionCode);
5718                } else {
5719                    // The current app on the system partition is better than
5720                    // what we have updated to on the data partition; switch
5721                    // back to the system partition version.
5722                    // At this point, its safely assumed that package installation for
5723                    // apps in system partition will go through. If not there won't be a working
5724                    // version of the app
5725                    // writer
5726                    synchronized (mPackages) {
5727                        // Just remove the loaded entries from package lists.
5728                        mPackages.remove(ps.name);
5729                    }
5730
5731                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5732                            + " reverting from " + ps.codePathString
5733                            + ": new version " + pkg.mVersionCode
5734                            + " better than installed " + ps.versionCode);
5735
5736                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5737                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5738                    synchronized (mInstallLock) {
5739                        args.cleanUpResourcesLI();
5740                    }
5741                    synchronized (mPackages) {
5742                        mSettings.enableSystemPackageLPw(ps.name);
5743                    }
5744                    updatedPkgBetter = true;
5745                }
5746            }
5747        }
5748
5749        if (updatedPkg != null) {
5750            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5751            // initially
5752            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5753
5754            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5755            // flag set initially
5756            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5757                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5758            }
5759        }
5760
5761        // Verify certificates against what was last scanned
5762        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5763
5764        /*
5765         * A new system app appeared, but we already had a non-system one of the
5766         * same name installed earlier.
5767         */
5768        boolean shouldHideSystemApp = false;
5769        if (updatedPkg == null && ps != null
5770                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5771            /*
5772             * Check to make sure the signatures match first. If they don't,
5773             * wipe the installed application and its data.
5774             */
5775            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5776                    != PackageManager.SIGNATURE_MATCH) {
5777                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5778                        + " signatures don't match existing userdata copy; removing");
5779                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5780                ps = null;
5781            } else {
5782                /*
5783                 * If the newly-added system app is an older version than the
5784                 * already installed version, hide it. It will be scanned later
5785                 * and re-added like an update.
5786                 */
5787                if (pkg.mVersionCode <= ps.versionCode) {
5788                    shouldHideSystemApp = true;
5789                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5790                            + " but new version " + pkg.mVersionCode + " better than installed "
5791                            + ps.versionCode + "; hiding system");
5792                } else {
5793                    /*
5794                     * The newly found system app is a newer version that the
5795                     * one previously installed. Simply remove the
5796                     * already-installed application and replace it with our own
5797                     * while keeping the application data.
5798                     */
5799                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5800                            + " reverting from " + ps.codePathString + ": new version "
5801                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5802                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5803                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5804                    synchronized (mInstallLock) {
5805                        args.cleanUpResourcesLI();
5806                    }
5807                }
5808            }
5809        }
5810
5811        // The apk is forward locked (not public) if its code and resources
5812        // are kept in different files. (except for app in either system or
5813        // vendor path).
5814        // TODO grab this value from PackageSettings
5815        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5816            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5817                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5818            }
5819        }
5820
5821        // TODO: extend to support forward-locked splits
5822        String resourcePath = null;
5823        String baseResourcePath = null;
5824        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5825            if (ps != null && ps.resourcePathString != null) {
5826                resourcePath = ps.resourcePathString;
5827                baseResourcePath = ps.resourcePathString;
5828            } else {
5829                // Should not happen at all. Just log an error.
5830                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5831            }
5832        } else {
5833            resourcePath = pkg.codePath;
5834            baseResourcePath = pkg.baseCodePath;
5835        }
5836
5837        // Set application objects path explicitly.
5838        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5839        pkg.applicationInfo.setCodePath(pkg.codePath);
5840        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5841        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5842        pkg.applicationInfo.setResourcePath(resourcePath);
5843        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5844        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5845
5846        // Note that we invoke the following method only if we are about to unpack an application
5847        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5848                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5849
5850        /*
5851         * If the system app should be overridden by a previously installed
5852         * data, hide the system app now and let the /data/app scan pick it up
5853         * again.
5854         */
5855        if (shouldHideSystemApp) {
5856            synchronized (mPackages) {
5857                /*
5858                 * We have to grant systems permissions before we hide, because
5859                 * grantPermissions will assume the package update is trying to
5860                 * expand its permissions.
5861                 */
5862                grantPermissionsLPw(pkg, true, pkg.packageName);
5863                mSettings.disableSystemPackageLPw(pkg.packageName);
5864            }
5865        }
5866
5867        return scannedPkg;
5868    }
5869
5870    private static String fixProcessName(String defProcessName,
5871            String processName, int uid) {
5872        if (processName == null) {
5873            return defProcessName;
5874        }
5875        return processName;
5876    }
5877
5878    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5879            throws PackageManagerException {
5880        if (pkgSetting.signatures.mSignatures != null) {
5881            // Already existing package. Make sure signatures match
5882            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5883                    == PackageManager.SIGNATURE_MATCH;
5884            if (!match) {
5885                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5886                        == PackageManager.SIGNATURE_MATCH;
5887            }
5888            if (!match) {
5889                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5890                        == PackageManager.SIGNATURE_MATCH;
5891            }
5892            if (!match) {
5893                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5894                        + pkg.packageName + " signatures do not match the "
5895                        + "previously installed version; ignoring!");
5896            }
5897        }
5898
5899        // Check for shared user signatures
5900        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5901            // Already existing package. Make sure signatures match
5902            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5903                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5904            if (!match) {
5905                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5906                        == PackageManager.SIGNATURE_MATCH;
5907            }
5908            if (!match) {
5909                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5910                        == PackageManager.SIGNATURE_MATCH;
5911            }
5912            if (!match) {
5913                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5914                        "Package " + pkg.packageName
5915                        + " has no signatures that match those in shared user "
5916                        + pkgSetting.sharedUser.name + "; ignoring!");
5917            }
5918        }
5919    }
5920
5921    /**
5922     * Enforces that only the system UID or root's UID can call a method exposed
5923     * via Binder.
5924     *
5925     * @param message used as message if SecurityException is thrown
5926     * @throws SecurityException if the caller is not system or root
5927     */
5928    private static final void enforceSystemOrRoot(String message) {
5929        final int uid = Binder.getCallingUid();
5930        if (uid != Process.SYSTEM_UID && uid != 0) {
5931            throw new SecurityException(message);
5932        }
5933    }
5934
5935    @Override
5936    public void performBootDexOpt() {
5937        enforceSystemOrRoot("Only the system can request dexopt be performed");
5938
5939        // Before everything else, see whether we need to fstrim.
5940        try {
5941            IMountService ms = PackageHelper.getMountService();
5942            if (ms != null) {
5943                final boolean isUpgrade = isUpgrade();
5944                boolean doTrim = isUpgrade;
5945                if (doTrim) {
5946                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5947                } else {
5948                    final long interval = android.provider.Settings.Global.getLong(
5949                            mContext.getContentResolver(),
5950                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5951                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5952                    if (interval > 0) {
5953                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5954                        if (timeSinceLast > interval) {
5955                            doTrim = true;
5956                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5957                                    + "; running immediately");
5958                        }
5959                    }
5960                }
5961                if (doTrim) {
5962                    if (!isFirstBoot()) {
5963                        try {
5964                            ActivityManagerNative.getDefault().showBootMessage(
5965                                    mContext.getResources().getString(
5966                                            R.string.android_upgrading_fstrim), true);
5967                        } catch (RemoteException e) {
5968                        }
5969                    }
5970                    ms.runMaintenance();
5971                }
5972            } else {
5973                Slog.e(TAG, "Mount service unavailable!");
5974            }
5975        } catch (RemoteException e) {
5976            // Can't happen; MountService is local
5977        }
5978
5979        final ArraySet<PackageParser.Package> pkgs;
5980        synchronized (mPackages) {
5981            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5982        }
5983
5984        if (pkgs != null) {
5985            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5986            // in case the device runs out of space.
5987            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5988            // Give priority to core apps.
5989            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5990                PackageParser.Package pkg = it.next();
5991                if (pkg.coreApp) {
5992                    if (DEBUG_DEXOPT) {
5993                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5994                    }
5995                    sortedPkgs.add(pkg);
5996                    it.remove();
5997                }
5998            }
5999            // Give priority to system apps that listen for pre boot complete.
6000            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6001            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6002            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6003                PackageParser.Package pkg = it.next();
6004                if (pkgNames.contains(pkg.packageName)) {
6005                    if (DEBUG_DEXOPT) {
6006                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6007                    }
6008                    sortedPkgs.add(pkg);
6009                    it.remove();
6010                }
6011            }
6012            // Give priority to system apps.
6013            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6014                PackageParser.Package pkg = it.next();
6015                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6016                    if (DEBUG_DEXOPT) {
6017                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6018                    }
6019                    sortedPkgs.add(pkg);
6020                    it.remove();
6021                }
6022            }
6023            // Give priority to updated system apps.
6024            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6025                PackageParser.Package pkg = it.next();
6026                if (pkg.isUpdatedSystemApp()) {
6027                    if (DEBUG_DEXOPT) {
6028                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6029                    }
6030                    sortedPkgs.add(pkg);
6031                    it.remove();
6032                }
6033            }
6034            // Give priority to apps that listen for boot complete.
6035            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6036            pkgNames = getPackageNamesForIntent(intent);
6037            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6038                PackageParser.Package pkg = it.next();
6039                if (pkgNames.contains(pkg.packageName)) {
6040                    if (DEBUG_DEXOPT) {
6041                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6042                    }
6043                    sortedPkgs.add(pkg);
6044                    it.remove();
6045                }
6046            }
6047            // Filter out packages that aren't recently used.
6048            filterRecentlyUsedApps(pkgs);
6049            // Add all remaining apps.
6050            for (PackageParser.Package pkg : pkgs) {
6051                if (DEBUG_DEXOPT) {
6052                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6053                }
6054                sortedPkgs.add(pkg);
6055            }
6056
6057            // If we want to be lazy, filter everything that wasn't recently used.
6058            if (mLazyDexOpt) {
6059                filterRecentlyUsedApps(sortedPkgs);
6060            }
6061
6062            int i = 0;
6063            int total = sortedPkgs.size();
6064            File dataDir = Environment.getDataDirectory();
6065            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6066            if (lowThreshold == 0) {
6067                throw new IllegalStateException("Invalid low memory threshold");
6068            }
6069            for (PackageParser.Package pkg : sortedPkgs) {
6070                long usableSpace = dataDir.getUsableSpace();
6071                if (usableSpace < lowThreshold) {
6072                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6073                    break;
6074                }
6075                performBootDexOpt(pkg, ++i, total);
6076            }
6077        }
6078    }
6079
6080    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6081        // Filter out packages that aren't recently used.
6082        //
6083        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6084        // should do a full dexopt.
6085        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6086            int total = pkgs.size();
6087            int skipped = 0;
6088            long now = System.currentTimeMillis();
6089            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6090                PackageParser.Package pkg = i.next();
6091                long then = pkg.mLastPackageUsageTimeInMills;
6092                if (then + mDexOptLRUThresholdInMills < now) {
6093                    if (DEBUG_DEXOPT) {
6094                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6095                              ((then == 0) ? "never" : new Date(then)));
6096                    }
6097                    i.remove();
6098                    skipped++;
6099                }
6100            }
6101            if (DEBUG_DEXOPT) {
6102                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6103            }
6104        }
6105    }
6106
6107    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6108        List<ResolveInfo> ris = null;
6109        try {
6110            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6111                    intent, null, 0, UserHandle.USER_OWNER);
6112        } catch (RemoteException e) {
6113        }
6114        ArraySet<String> pkgNames = new ArraySet<String>();
6115        if (ris != null) {
6116            for (ResolveInfo ri : ris) {
6117                pkgNames.add(ri.activityInfo.packageName);
6118            }
6119        }
6120        return pkgNames;
6121    }
6122
6123    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6124        if (DEBUG_DEXOPT) {
6125            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6126        }
6127        if (!isFirstBoot()) {
6128            try {
6129                ActivityManagerNative.getDefault().showBootMessage(
6130                        mContext.getResources().getString(R.string.android_upgrading_apk,
6131                                curr, total), true);
6132            } catch (RemoteException e) {
6133            }
6134        }
6135        PackageParser.Package p = pkg;
6136        synchronized (mInstallLock) {
6137            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6138                    false /* force dex */, false /* defer */, true /* include dependencies */);
6139        }
6140    }
6141
6142    @Override
6143    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6144        return performDexOpt(packageName, instructionSet, false);
6145    }
6146
6147    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6148        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6149        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6150        if (!dexopt && !updateUsage) {
6151            // We aren't going to dexopt or update usage, so bail early.
6152            return false;
6153        }
6154        PackageParser.Package p;
6155        final String targetInstructionSet;
6156        synchronized (mPackages) {
6157            p = mPackages.get(packageName);
6158            if (p == null) {
6159                return false;
6160            }
6161            if (updateUsage) {
6162                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6163            }
6164            mPackageUsage.write(false);
6165            if (!dexopt) {
6166                // We aren't going to dexopt, so bail early.
6167                return false;
6168            }
6169
6170            targetInstructionSet = instructionSet != null ? instructionSet :
6171                    getPrimaryInstructionSet(p.applicationInfo);
6172            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6173                return false;
6174            }
6175        }
6176
6177        synchronized (mInstallLock) {
6178            final String[] instructionSets = new String[] { targetInstructionSet };
6179            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6180                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6181            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6182        }
6183    }
6184
6185    public ArraySet<String> getPackagesThatNeedDexOpt() {
6186        ArraySet<String> pkgs = null;
6187        synchronized (mPackages) {
6188            for (PackageParser.Package p : mPackages.values()) {
6189                if (DEBUG_DEXOPT) {
6190                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6191                }
6192                if (!p.mDexOptPerformed.isEmpty()) {
6193                    continue;
6194                }
6195                if (pkgs == null) {
6196                    pkgs = new ArraySet<String>();
6197                }
6198                pkgs.add(p.packageName);
6199            }
6200        }
6201        return pkgs;
6202    }
6203
6204    public void shutdown() {
6205        mPackageUsage.write(true);
6206    }
6207
6208    @Override
6209    public void forceDexOpt(String packageName) {
6210        enforceSystemOrRoot("forceDexOpt");
6211
6212        PackageParser.Package pkg;
6213        synchronized (mPackages) {
6214            pkg = mPackages.get(packageName);
6215            if (pkg == null) {
6216                throw new IllegalArgumentException("Missing package: " + packageName);
6217            }
6218        }
6219
6220        synchronized (mInstallLock) {
6221            final String[] instructionSets = new String[] {
6222                    getPrimaryInstructionSet(pkg.applicationInfo) };
6223            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6224                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6225            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6226                throw new IllegalStateException("Failed to dexopt: " + res);
6227            }
6228        }
6229    }
6230
6231    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6232        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6233            Slog.w(TAG, "Unable to update from " + oldPkg.name
6234                    + " to " + newPkg.packageName
6235                    + ": old package not in system partition");
6236            return false;
6237        } else if (mPackages.get(oldPkg.name) != null) {
6238            Slog.w(TAG, "Unable to update from " + oldPkg.name
6239                    + " to " + newPkg.packageName
6240                    + ": old package still exists");
6241            return false;
6242        }
6243        return true;
6244    }
6245
6246    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6247        int[] users = sUserManager.getUserIds();
6248        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6249        if (res < 0) {
6250            return res;
6251        }
6252        for (int user : users) {
6253            if (user != 0) {
6254                res = mInstaller.createUserData(volumeUuid, packageName,
6255                        UserHandle.getUid(user, uid), user, seinfo);
6256                if (res < 0) {
6257                    return res;
6258                }
6259            }
6260        }
6261        return res;
6262    }
6263
6264    private int removeDataDirsLI(String volumeUuid, String packageName) {
6265        int[] users = sUserManager.getUserIds();
6266        int res = 0;
6267        for (int user : users) {
6268            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6269            if (resInner < 0) {
6270                res = resInner;
6271            }
6272        }
6273
6274        return res;
6275    }
6276
6277    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6278        int[] users = sUserManager.getUserIds();
6279        int res = 0;
6280        for (int user : users) {
6281            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6282            if (resInner < 0) {
6283                res = resInner;
6284            }
6285        }
6286        return res;
6287    }
6288
6289    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6290            PackageParser.Package changingLib) {
6291        if (file.path != null) {
6292            usesLibraryFiles.add(file.path);
6293            return;
6294        }
6295        PackageParser.Package p = mPackages.get(file.apk);
6296        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6297            // If we are doing this while in the middle of updating a library apk,
6298            // then we need to make sure to use that new apk for determining the
6299            // dependencies here.  (We haven't yet finished committing the new apk
6300            // to the package manager state.)
6301            if (p == null || p.packageName.equals(changingLib.packageName)) {
6302                p = changingLib;
6303            }
6304        }
6305        if (p != null) {
6306            usesLibraryFiles.addAll(p.getAllCodePaths());
6307        }
6308    }
6309
6310    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6311            PackageParser.Package changingLib) throws PackageManagerException {
6312        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6313            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6314            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6315            for (int i=0; i<N; i++) {
6316                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6317                if (file == null) {
6318                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6319                            "Package " + pkg.packageName + " requires unavailable shared library "
6320                            + pkg.usesLibraries.get(i) + "; failing!");
6321                }
6322                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6323            }
6324            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6325            for (int i=0; i<N; i++) {
6326                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6327                if (file == null) {
6328                    Slog.w(TAG, "Package " + pkg.packageName
6329                            + " desires unavailable shared library "
6330                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6331                } else {
6332                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6333                }
6334            }
6335            N = usesLibraryFiles.size();
6336            if (N > 0) {
6337                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6338            } else {
6339                pkg.usesLibraryFiles = null;
6340            }
6341        }
6342    }
6343
6344    private static boolean hasString(List<String> list, List<String> which) {
6345        if (list == null) {
6346            return false;
6347        }
6348        for (int i=list.size()-1; i>=0; i--) {
6349            for (int j=which.size()-1; j>=0; j--) {
6350                if (which.get(j).equals(list.get(i))) {
6351                    return true;
6352                }
6353            }
6354        }
6355        return false;
6356    }
6357
6358    private void updateAllSharedLibrariesLPw() {
6359        for (PackageParser.Package pkg : mPackages.values()) {
6360            try {
6361                updateSharedLibrariesLPw(pkg, null);
6362            } catch (PackageManagerException e) {
6363                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6364            }
6365        }
6366    }
6367
6368    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6369            PackageParser.Package changingPkg) {
6370        ArrayList<PackageParser.Package> res = null;
6371        for (PackageParser.Package pkg : mPackages.values()) {
6372            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6373                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6374                if (res == null) {
6375                    res = new ArrayList<PackageParser.Package>();
6376                }
6377                res.add(pkg);
6378                try {
6379                    updateSharedLibrariesLPw(pkg, changingPkg);
6380                } catch (PackageManagerException e) {
6381                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6382                }
6383            }
6384        }
6385        return res;
6386    }
6387
6388    /**
6389     * Derive the value of the {@code cpuAbiOverride} based on the provided
6390     * value and an optional stored value from the package settings.
6391     */
6392    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6393        String cpuAbiOverride = null;
6394
6395        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6396            cpuAbiOverride = null;
6397        } else if (abiOverride != null) {
6398            cpuAbiOverride = abiOverride;
6399        } else if (settings != null) {
6400            cpuAbiOverride = settings.cpuAbiOverrideString;
6401        }
6402
6403        return cpuAbiOverride;
6404    }
6405
6406    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6407            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6408        boolean success = false;
6409        try {
6410            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6411                    currentTime, user);
6412            success = true;
6413            return res;
6414        } finally {
6415            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6416                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6417            }
6418        }
6419    }
6420
6421    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6422            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6423        final File scanFile = new File(pkg.codePath);
6424        if (pkg.applicationInfo.getCodePath() == null ||
6425                pkg.applicationInfo.getResourcePath() == null) {
6426            // Bail out. The resource and code paths haven't been set.
6427            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6428                    "Code and resource paths haven't been set correctly");
6429        }
6430
6431        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6432            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6433        } else {
6434            // Only allow system apps to be flagged as core apps.
6435            pkg.coreApp = false;
6436        }
6437
6438        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6439            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6440        }
6441
6442        if (mCustomResolverComponentName != null &&
6443                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6444            setUpCustomResolverActivity(pkg);
6445        }
6446
6447        if (pkg.packageName.equals("android")) {
6448            synchronized (mPackages) {
6449                if (mAndroidApplication != null) {
6450                    Slog.w(TAG, "*************************************************");
6451                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6452                    Slog.w(TAG, " file=" + scanFile);
6453                    Slog.w(TAG, "*************************************************");
6454                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6455                            "Core android package being redefined.  Skipping.");
6456                }
6457
6458                // Set up information for our fall-back user intent resolution activity.
6459                mPlatformPackage = pkg;
6460                pkg.mVersionCode = mSdkVersion;
6461                mAndroidApplication = pkg.applicationInfo;
6462
6463                if (!mResolverReplaced) {
6464                    mResolveActivity.applicationInfo = mAndroidApplication;
6465                    mResolveActivity.name = ResolverActivity.class.getName();
6466                    mResolveActivity.packageName = mAndroidApplication.packageName;
6467                    mResolveActivity.processName = "system:ui";
6468                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6469                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6470                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6471                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6472                    mResolveActivity.exported = true;
6473                    mResolveActivity.enabled = true;
6474                    mResolveInfo.activityInfo = mResolveActivity;
6475                    mResolveInfo.priority = 0;
6476                    mResolveInfo.preferredOrder = 0;
6477                    mResolveInfo.match = 0;
6478                    mResolveComponentName = new ComponentName(
6479                            mAndroidApplication.packageName, mResolveActivity.name);
6480                }
6481            }
6482        }
6483
6484        if (DEBUG_PACKAGE_SCANNING) {
6485            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6486                Log.d(TAG, "Scanning package " + pkg.packageName);
6487        }
6488
6489        if (mPackages.containsKey(pkg.packageName)
6490                || mSharedLibraries.containsKey(pkg.packageName)) {
6491            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6492                    "Application package " + pkg.packageName
6493                    + " already installed.  Skipping duplicate.");
6494        }
6495
6496        // If we're only installing presumed-existing packages, require that the
6497        // scanned APK is both already known and at the path previously established
6498        // for it.  Previously unknown packages we pick up normally, but if we have an
6499        // a priori expectation about this package's install presence, enforce it.
6500        // With a singular exception for new system packages. When an OTA contains
6501        // a new system package, we allow the codepath to change from a system location
6502        // to the user-installed location. If we don't allow this change, any newer,
6503        // user-installed version of the application will be ignored.
6504        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6505            if (mExpectingBetter.containsKey(pkg.packageName)) {
6506                logCriticalInfo(Log.WARN,
6507                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6508            } else {
6509                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6510                if (known != null) {
6511                    if (DEBUG_PACKAGE_SCANNING) {
6512                        Log.d(TAG, "Examining " + pkg.codePath
6513                                + " and requiring known paths " + known.codePathString
6514                                + " & " + known.resourcePathString);
6515                    }
6516                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6517                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6518                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6519                                "Application package " + pkg.packageName
6520                                + " found at " + pkg.applicationInfo.getCodePath()
6521                                + " but expected at " + known.codePathString + "; ignoring.");
6522                    }
6523                }
6524            }
6525        }
6526
6527        // Initialize package source and resource directories
6528        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6529        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6530
6531        SharedUserSetting suid = null;
6532        PackageSetting pkgSetting = null;
6533
6534        if (!isSystemApp(pkg)) {
6535            // Only system apps can use these features.
6536            pkg.mOriginalPackages = null;
6537            pkg.mRealPackage = null;
6538            pkg.mAdoptPermissions = null;
6539        }
6540
6541        // writer
6542        synchronized (mPackages) {
6543            if (pkg.mSharedUserId != null) {
6544                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6545                if (suid == null) {
6546                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6547                            "Creating application package " + pkg.packageName
6548                            + " for shared user failed");
6549                }
6550                if (DEBUG_PACKAGE_SCANNING) {
6551                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6552                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6553                                + "): packages=" + suid.packages);
6554                }
6555            }
6556
6557            // Check if we are renaming from an original package name.
6558            PackageSetting origPackage = null;
6559            String realName = null;
6560            if (pkg.mOriginalPackages != null) {
6561                // This package may need to be renamed to a previously
6562                // installed name.  Let's check on that...
6563                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6564                if (pkg.mOriginalPackages.contains(renamed)) {
6565                    // This package had originally been installed as the
6566                    // original name, and we have already taken care of
6567                    // transitioning to the new one.  Just update the new
6568                    // one to continue using the old name.
6569                    realName = pkg.mRealPackage;
6570                    if (!pkg.packageName.equals(renamed)) {
6571                        // Callers into this function may have already taken
6572                        // care of renaming the package; only do it here if
6573                        // it is not already done.
6574                        pkg.setPackageName(renamed);
6575                    }
6576
6577                } else {
6578                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6579                        if ((origPackage = mSettings.peekPackageLPr(
6580                                pkg.mOriginalPackages.get(i))) != null) {
6581                            // We do have the package already installed under its
6582                            // original name...  should we use it?
6583                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6584                                // New package is not compatible with original.
6585                                origPackage = null;
6586                                continue;
6587                            } else if (origPackage.sharedUser != null) {
6588                                // Make sure uid is compatible between packages.
6589                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6590                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6591                                            + " to " + pkg.packageName + ": old uid "
6592                                            + origPackage.sharedUser.name
6593                                            + " differs from " + pkg.mSharedUserId);
6594                                    origPackage = null;
6595                                    continue;
6596                                }
6597                            } else {
6598                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6599                                        + pkg.packageName + " to old name " + origPackage.name);
6600                            }
6601                            break;
6602                        }
6603                    }
6604                }
6605            }
6606
6607            if (mTransferedPackages.contains(pkg.packageName)) {
6608                Slog.w(TAG, "Package " + pkg.packageName
6609                        + " was transferred to another, but its .apk remains");
6610            }
6611
6612            // Just create the setting, don't add it yet. For already existing packages
6613            // the PkgSetting exists already and doesn't have to be created.
6614            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6615                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6616                    pkg.applicationInfo.primaryCpuAbi,
6617                    pkg.applicationInfo.secondaryCpuAbi,
6618                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6619                    user, false);
6620            if (pkgSetting == null) {
6621                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6622                        "Creating application package " + pkg.packageName + " failed");
6623            }
6624
6625            if (pkgSetting.origPackage != null) {
6626                // If we are first transitioning from an original package,
6627                // fix up the new package's name now.  We need to do this after
6628                // looking up the package under its new name, so getPackageLP
6629                // can take care of fiddling things correctly.
6630                pkg.setPackageName(origPackage.name);
6631
6632                // File a report about this.
6633                String msg = "New package " + pkgSetting.realName
6634                        + " renamed to replace old package " + pkgSetting.name;
6635                reportSettingsProblem(Log.WARN, msg);
6636
6637                // Make a note of it.
6638                mTransferedPackages.add(origPackage.name);
6639
6640                // No longer need to retain this.
6641                pkgSetting.origPackage = null;
6642            }
6643
6644            if (realName != null) {
6645                // Make a note of it.
6646                mTransferedPackages.add(pkg.packageName);
6647            }
6648
6649            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6650                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6651            }
6652
6653            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6654                // Check all shared libraries and map to their actual file path.
6655                // We only do this here for apps not on a system dir, because those
6656                // are the only ones that can fail an install due to this.  We
6657                // will take care of the system apps by updating all of their
6658                // library paths after the scan is done.
6659                updateSharedLibrariesLPw(pkg, null);
6660            }
6661
6662            if (mFoundPolicyFile) {
6663                SELinuxMMAC.assignSeinfoValue(pkg);
6664            }
6665
6666            pkg.applicationInfo.uid = pkgSetting.appId;
6667            pkg.mExtras = pkgSetting;
6668            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6669                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6670                    // We just determined the app is signed correctly, so bring
6671                    // over the latest parsed certs.
6672                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6673                } else {
6674                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6675                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6676                                "Package " + pkg.packageName + " upgrade keys do not match the "
6677                                + "previously installed version");
6678                    } else {
6679                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6680                        String msg = "System package " + pkg.packageName
6681                            + " signature changed; retaining data.";
6682                        reportSettingsProblem(Log.WARN, msg);
6683                    }
6684                }
6685            } else {
6686                try {
6687                    verifySignaturesLP(pkgSetting, pkg);
6688                    // We just determined the app is signed correctly, so bring
6689                    // over the latest parsed certs.
6690                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6691                } catch (PackageManagerException e) {
6692                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6693                        throw e;
6694                    }
6695                    // The signature has changed, but this package is in the system
6696                    // image...  let's recover!
6697                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6698                    // However...  if this package is part of a shared user, but it
6699                    // doesn't match the signature of the shared user, let's fail.
6700                    // What this means is that you can't change the signatures
6701                    // associated with an overall shared user, which doesn't seem all
6702                    // that unreasonable.
6703                    if (pkgSetting.sharedUser != null) {
6704                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6705                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6706                            throw new PackageManagerException(
6707                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6708                                            "Signature mismatch for shared user : "
6709                                            + pkgSetting.sharedUser);
6710                        }
6711                    }
6712                    // File a report about this.
6713                    String msg = "System package " + pkg.packageName
6714                        + " signature changed; retaining data.";
6715                    reportSettingsProblem(Log.WARN, msg);
6716                }
6717            }
6718            // Verify that this new package doesn't have any content providers
6719            // that conflict with existing packages.  Only do this if the
6720            // package isn't already installed, since we don't want to break
6721            // things that are installed.
6722            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6723                final int N = pkg.providers.size();
6724                int i;
6725                for (i=0; i<N; i++) {
6726                    PackageParser.Provider p = pkg.providers.get(i);
6727                    if (p.info.authority != null) {
6728                        String names[] = p.info.authority.split(";");
6729                        for (int j = 0; j < names.length; j++) {
6730                            if (mProvidersByAuthority.containsKey(names[j])) {
6731                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6732                                final String otherPackageName =
6733                                        ((other != null && other.getComponentName() != null) ?
6734                                                other.getComponentName().getPackageName() : "?");
6735                                throw new PackageManagerException(
6736                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6737                                                "Can't install because provider name " + names[j]
6738                                                + " (in package " + pkg.applicationInfo.packageName
6739                                                + ") is already used by " + otherPackageName);
6740                            }
6741                        }
6742                    }
6743                }
6744            }
6745
6746            if (pkg.mAdoptPermissions != null) {
6747                // This package wants to adopt ownership of permissions from
6748                // another package.
6749                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6750                    final String origName = pkg.mAdoptPermissions.get(i);
6751                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6752                    if (orig != null) {
6753                        if (verifyPackageUpdateLPr(orig, pkg)) {
6754                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6755                                    + pkg.packageName);
6756                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6757                        }
6758                    }
6759                }
6760            }
6761        }
6762
6763        final String pkgName = pkg.packageName;
6764
6765        final long scanFileTime = scanFile.lastModified();
6766        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6767        pkg.applicationInfo.processName = fixProcessName(
6768                pkg.applicationInfo.packageName,
6769                pkg.applicationInfo.processName,
6770                pkg.applicationInfo.uid);
6771
6772        File dataPath;
6773        if (mPlatformPackage == pkg) {
6774            // The system package is special.
6775            dataPath = new File(Environment.getDataDirectory(), "system");
6776
6777            pkg.applicationInfo.dataDir = dataPath.getPath();
6778
6779        } else {
6780            // This is a normal package, need to make its data directory.
6781            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6782                    UserHandle.USER_OWNER, pkg.packageName);
6783
6784            boolean uidError = false;
6785            if (dataPath.exists()) {
6786                int currentUid = 0;
6787                try {
6788                    StructStat stat = Os.stat(dataPath.getPath());
6789                    currentUid = stat.st_uid;
6790                } catch (ErrnoException e) {
6791                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6792                }
6793
6794                // If we have mismatched owners for the data path, we have a problem.
6795                if (currentUid != pkg.applicationInfo.uid) {
6796                    boolean recovered = false;
6797                    if (currentUid == 0) {
6798                        // The directory somehow became owned by root.  Wow.
6799                        // This is probably because the system was stopped while
6800                        // installd was in the middle of messing with its libs
6801                        // directory.  Ask installd to fix that.
6802                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6803                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6804                        if (ret >= 0) {
6805                            recovered = true;
6806                            String msg = "Package " + pkg.packageName
6807                                    + " unexpectedly changed to uid 0; recovered to " +
6808                                    + pkg.applicationInfo.uid;
6809                            reportSettingsProblem(Log.WARN, msg);
6810                        }
6811                    }
6812                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6813                            || (scanFlags&SCAN_BOOTING) != 0)) {
6814                        // If this is a system app, we can at least delete its
6815                        // current data so the application will still work.
6816                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6817                        if (ret >= 0) {
6818                            // TODO: Kill the processes first
6819                            // Old data gone!
6820                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6821                                    ? "System package " : "Third party package ";
6822                            String msg = prefix + pkg.packageName
6823                                    + " has changed from uid: "
6824                                    + currentUid + " to "
6825                                    + pkg.applicationInfo.uid + "; old data erased";
6826                            reportSettingsProblem(Log.WARN, msg);
6827                            recovered = true;
6828
6829                            // And now re-install the app.
6830                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6831                                    pkg.applicationInfo.seinfo);
6832                            if (ret == -1) {
6833                                // Ack should not happen!
6834                                msg = prefix + pkg.packageName
6835                                        + " could not have data directory re-created after delete.";
6836                                reportSettingsProblem(Log.WARN, msg);
6837                                throw new PackageManagerException(
6838                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6839                            }
6840                        }
6841                        if (!recovered) {
6842                            mHasSystemUidErrors = true;
6843                        }
6844                    } else if (!recovered) {
6845                        // If we allow this install to proceed, we will be broken.
6846                        // Abort, abort!
6847                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6848                                "scanPackageLI");
6849                    }
6850                    if (!recovered) {
6851                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6852                            + pkg.applicationInfo.uid + "/fs_"
6853                            + currentUid;
6854                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6855                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6856                        String msg = "Package " + pkg.packageName
6857                                + " has mismatched uid: "
6858                                + currentUid + " on disk, "
6859                                + pkg.applicationInfo.uid + " in settings";
6860                        // writer
6861                        synchronized (mPackages) {
6862                            mSettings.mReadMessages.append(msg);
6863                            mSettings.mReadMessages.append('\n');
6864                            uidError = true;
6865                            if (!pkgSetting.uidError) {
6866                                reportSettingsProblem(Log.ERROR, msg);
6867                            }
6868                        }
6869                    }
6870                }
6871                pkg.applicationInfo.dataDir = dataPath.getPath();
6872                if (mShouldRestoreconData) {
6873                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6874                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6875                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6876                }
6877            } else {
6878                if (DEBUG_PACKAGE_SCANNING) {
6879                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6880                        Log.v(TAG, "Want this data dir: " + dataPath);
6881                }
6882                //invoke installer to do the actual installation
6883                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6884                        pkg.applicationInfo.seinfo);
6885                if (ret < 0) {
6886                    // Error from installer
6887                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6888                            "Unable to create data dirs [errorCode=" + ret + "]");
6889                }
6890
6891                if (dataPath.exists()) {
6892                    pkg.applicationInfo.dataDir = dataPath.getPath();
6893                } else {
6894                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6895                    pkg.applicationInfo.dataDir = null;
6896                }
6897            }
6898
6899            pkgSetting.uidError = uidError;
6900        }
6901
6902        final String path = scanFile.getPath();
6903        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6904
6905        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6906            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6907
6908            // Some system apps still use directory structure for native libraries
6909            // in which case we might end up not detecting abi solely based on apk
6910            // structure. Try to detect abi based on directory structure.
6911            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6912                    pkg.applicationInfo.primaryCpuAbi == null) {
6913                setBundledAppAbisAndRoots(pkg, pkgSetting);
6914                setNativeLibraryPaths(pkg);
6915            }
6916
6917        } else {
6918            if ((scanFlags & SCAN_MOVE) != 0) {
6919                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6920                // but we already have this packages package info in the PackageSetting. We just
6921                // use that and derive the native library path based on the new codepath.
6922                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6923                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6924            }
6925
6926            // Set native library paths again. For moves, the path will be updated based on the
6927            // ABIs we've determined above. For non-moves, the path will be updated based on the
6928            // ABIs we determined during compilation, but the path will depend on the final
6929            // package path (after the rename away from the stage path).
6930            setNativeLibraryPaths(pkg);
6931        }
6932
6933        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6934        final int[] userIds = sUserManager.getUserIds();
6935        synchronized (mInstallLock) {
6936            // Make sure all user data directories are ready to roll; we're okay
6937            // if they already exist
6938            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6939                for (int userId : userIds) {
6940                    if (userId != 0) {
6941                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6942                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6943                                pkg.applicationInfo.seinfo);
6944                    }
6945                }
6946            }
6947
6948            // Create a native library symlink only if we have native libraries
6949            // and if the native libraries are 32 bit libraries. We do not provide
6950            // this symlink for 64 bit libraries.
6951            if (pkg.applicationInfo.primaryCpuAbi != null &&
6952                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6953                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6954                for (int userId : userIds) {
6955                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6956                            nativeLibPath, userId) < 0) {
6957                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6958                                "Failed linking native library dir (user=" + userId + ")");
6959                    }
6960                }
6961            }
6962        }
6963
6964        // This is a special case for the "system" package, where the ABI is
6965        // dictated by the zygote configuration (and init.rc). We should keep track
6966        // of this ABI so that we can deal with "normal" applications that run under
6967        // the same UID correctly.
6968        if (mPlatformPackage == pkg) {
6969            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6970                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6971        }
6972
6973        // If there's a mismatch between the abi-override in the package setting
6974        // and the abiOverride specified for the install. Warn about this because we
6975        // would've already compiled the app without taking the package setting into
6976        // account.
6977        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6978            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6979                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6980                        " for package: " + pkg.packageName);
6981            }
6982        }
6983
6984        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6985        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6986        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6987
6988        // Copy the derived override back to the parsed package, so that we can
6989        // update the package settings accordingly.
6990        pkg.cpuAbiOverride = cpuAbiOverride;
6991
6992        if (DEBUG_ABI_SELECTION) {
6993            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6994                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6995                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6996        }
6997
6998        // Push the derived path down into PackageSettings so we know what to
6999        // clean up at uninstall time.
7000        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7001
7002        if (DEBUG_ABI_SELECTION) {
7003            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7004                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7005                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7006        }
7007
7008        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7009            // We don't do this here during boot because we can do it all
7010            // at once after scanning all existing packages.
7011            //
7012            // We also do this *before* we perform dexopt on this package, so that
7013            // we can avoid redundant dexopts, and also to make sure we've got the
7014            // code and package path correct.
7015            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7016                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7017        }
7018
7019        if ((scanFlags & SCAN_NO_DEX) == 0) {
7020            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7021                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7022            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7023                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7024            }
7025        }
7026        if (mFactoryTest && pkg.requestedPermissions.contains(
7027                android.Manifest.permission.FACTORY_TEST)) {
7028            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7029        }
7030
7031        ArrayList<PackageParser.Package> clientLibPkgs = null;
7032
7033        // writer
7034        synchronized (mPackages) {
7035            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7036                // Only system apps can add new shared libraries.
7037                if (pkg.libraryNames != null) {
7038                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7039                        String name = pkg.libraryNames.get(i);
7040                        boolean allowed = false;
7041                        if (pkg.isUpdatedSystemApp()) {
7042                            // New library entries can only be added through the
7043                            // system image.  This is important to get rid of a lot
7044                            // of nasty edge cases: for example if we allowed a non-
7045                            // system update of the app to add a library, then uninstalling
7046                            // the update would make the library go away, and assumptions
7047                            // we made such as through app install filtering would now
7048                            // have allowed apps on the device which aren't compatible
7049                            // with it.  Better to just have the restriction here, be
7050                            // conservative, and create many fewer cases that can negatively
7051                            // impact the user experience.
7052                            final PackageSetting sysPs = mSettings
7053                                    .getDisabledSystemPkgLPr(pkg.packageName);
7054                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7055                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7056                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7057                                        allowed = true;
7058                                        allowed = true;
7059                                        break;
7060                                    }
7061                                }
7062                            }
7063                        } else {
7064                            allowed = true;
7065                        }
7066                        if (allowed) {
7067                            if (!mSharedLibraries.containsKey(name)) {
7068                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7069                            } else if (!name.equals(pkg.packageName)) {
7070                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7071                                        + name + " already exists; skipping");
7072                            }
7073                        } else {
7074                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7075                                    + name + " that is not declared on system image; skipping");
7076                        }
7077                    }
7078                    if ((scanFlags&SCAN_BOOTING) == 0) {
7079                        // If we are not booting, we need to update any applications
7080                        // that are clients of our shared library.  If we are booting,
7081                        // this will all be done once the scan is complete.
7082                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7083                    }
7084                }
7085            }
7086        }
7087
7088        // We also need to dexopt any apps that are dependent on this library.  Note that
7089        // if these fail, we should abort the install since installing the library will
7090        // result in some apps being broken.
7091        if (clientLibPkgs != null) {
7092            if ((scanFlags & SCAN_NO_DEX) == 0) {
7093                for (int i = 0; i < clientLibPkgs.size(); i++) {
7094                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7095                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7096                            null /* instruction sets */, forceDex,
7097                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7098                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7099                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7100                                "scanPackageLI failed to dexopt clientLibPkgs");
7101                    }
7102                }
7103            }
7104        }
7105
7106        // Also need to kill any apps that are dependent on the library.
7107        if (clientLibPkgs != null) {
7108            for (int i=0; i<clientLibPkgs.size(); i++) {
7109                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7110                killApplication(clientPkg.applicationInfo.packageName,
7111                        clientPkg.applicationInfo.uid, "update lib");
7112            }
7113        }
7114
7115        // Make sure we're not adding any bogus keyset info
7116        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7117        ksms.assertScannedPackageValid(pkg);
7118
7119        // writer
7120        synchronized (mPackages) {
7121            // We don't expect installation to fail beyond this point
7122
7123            // Add the new setting to mSettings
7124            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7125            // Add the new setting to mPackages
7126            mPackages.put(pkg.applicationInfo.packageName, pkg);
7127            // Make sure we don't accidentally delete its data.
7128            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7129            while (iter.hasNext()) {
7130                PackageCleanItem item = iter.next();
7131                if (pkgName.equals(item.packageName)) {
7132                    iter.remove();
7133                }
7134            }
7135
7136            // Take care of first install / last update times.
7137            if (currentTime != 0) {
7138                if (pkgSetting.firstInstallTime == 0) {
7139                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7140                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7141                    pkgSetting.lastUpdateTime = currentTime;
7142                }
7143            } else if (pkgSetting.firstInstallTime == 0) {
7144                // We need *something*.  Take time time stamp of the file.
7145                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7146            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7147                if (scanFileTime != pkgSetting.timeStamp) {
7148                    // A package on the system image has changed; consider this
7149                    // to be an update.
7150                    pkgSetting.lastUpdateTime = scanFileTime;
7151                }
7152            }
7153
7154            // Add the package's KeySets to the global KeySetManagerService
7155            ksms.addScannedPackageLPw(pkg);
7156
7157            int N = pkg.providers.size();
7158            StringBuilder r = null;
7159            int i;
7160            for (i=0; i<N; i++) {
7161                PackageParser.Provider p = pkg.providers.get(i);
7162                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7163                        p.info.processName, pkg.applicationInfo.uid);
7164                mProviders.addProvider(p);
7165                p.syncable = p.info.isSyncable;
7166                if (p.info.authority != null) {
7167                    String names[] = p.info.authority.split(";");
7168                    p.info.authority = null;
7169                    for (int j = 0; j < names.length; j++) {
7170                        if (j == 1 && p.syncable) {
7171                            // We only want the first authority for a provider to possibly be
7172                            // syncable, so if we already added this provider using a different
7173                            // authority clear the syncable flag. We copy the provider before
7174                            // changing it because the mProviders object contains a reference
7175                            // to a provider that we don't want to change.
7176                            // Only do this for the second authority since the resulting provider
7177                            // object can be the same for all future authorities for this provider.
7178                            p = new PackageParser.Provider(p);
7179                            p.syncable = false;
7180                        }
7181                        if (!mProvidersByAuthority.containsKey(names[j])) {
7182                            mProvidersByAuthority.put(names[j], p);
7183                            if (p.info.authority == null) {
7184                                p.info.authority = names[j];
7185                            } else {
7186                                p.info.authority = p.info.authority + ";" + names[j];
7187                            }
7188                            if (DEBUG_PACKAGE_SCANNING) {
7189                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7190                                    Log.d(TAG, "Registered content provider: " + names[j]
7191                                            + ", className = " + p.info.name + ", isSyncable = "
7192                                            + p.info.isSyncable);
7193                            }
7194                        } else {
7195                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7196                            Slog.w(TAG, "Skipping provider name " + names[j] +
7197                                    " (in package " + pkg.applicationInfo.packageName +
7198                                    "): name already used by "
7199                                    + ((other != null && other.getComponentName() != null)
7200                                            ? other.getComponentName().getPackageName() : "?"));
7201                        }
7202                    }
7203                }
7204                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7205                    if (r == null) {
7206                        r = new StringBuilder(256);
7207                    } else {
7208                        r.append(' ');
7209                    }
7210                    r.append(p.info.name);
7211                }
7212            }
7213            if (r != null) {
7214                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7215            }
7216
7217            N = pkg.services.size();
7218            r = null;
7219            for (i=0; i<N; i++) {
7220                PackageParser.Service s = pkg.services.get(i);
7221                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7222                        s.info.processName, pkg.applicationInfo.uid);
7223                mServices.addService(s);
7224                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7225                    if (r == null) {
7226                        r = new StringBuilder(256);
7227                    } else {
7228                        r.append(' ');
7229                    }
7230                    r.append(s.info.name);
7231                }
7232            }
7233            if (r != null) {
7234                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7235            }
7236
7237            N = pkg.receivers.size();
7238            r = null;
7239            for (i=0; i<N; i++) {
7240                PackageParser.Activity a = pkg.receivers.get(i);
7241                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7242                        a.info.processName, pkg.applicationInfo.uid);
7243                mReceivers.addActivity(a, "receiver");
7244                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7245                    if (r == null) {
7246                        r = new StringBuilder(256);
7247                    } else {
7248                        r.append(' ');
7249                    }
7250                    r.append(a.info.name);
7251                }
7252            }
7253            if (r != null) {
7254                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7255            }
7256
7257            N = pkg.activities.size();
7258            r = null;
7259            for (i=0; i<N; i++) {
7260                PackageParser.Activity a = pkg.activities.get(i);
7261                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7262                        a.info.processName, pkg.applicationInfo.uid);
7263                mActivities.addActivity(a, "activity");
7264                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7265                    if (r == null) {
7266                        r = new StringBuilder(256);
7267                    } else {
7268                        r.append(' ');
7269                    }
7270                    r.append(a.info.name);
7271                }
7272            }
7273            if (r != null) {
7274                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7275            }
7276
7277            N = pkg.permissionGroups.size();
7278            r = null;
7279            for (i=0; i<N; i++) {
7280                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7281                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7282                if (cur == null) {
7283                    mPermissionGroups.put(pg.info.name, pg);
7284                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7285                        if (r == null) {
7286                            r = new StringBuilder(256);
7287                        } else {
7288                            r.append(' ');
7289                        }
7290                        r.append(pg.info.name);
7291                    }
7292                } else {
7293                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7294                            + pg.info.packageName + " ignored: original from "
7295                            + cur.info.packageName);
7296                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7297                        if (r == null) {
7298                            r = new StringBuilder(256);
7299                        } else {
7300                            r.append(' ');
7301                        }
7302                        r.append("DUP:");
7303                        r.append(pg.info.name);
7304                    }
7305                }
7306            }
7307            if (r != null) {
7308                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7309            }
7310
7311            N = pkg.permissions.size();
7312            r = null;
7313            for (i=0; i<N; i++) {
7314                PackageParser.Permission p = pkg.permissions.get(i);
7315
7316                // Now that permission groups have a special meaning, we ignore permission
7317                // groups for legacy apps to prevent unexpected behavior. In particular,
7318                // permissions for one app being granted to someone just becuase they happen
7319                // to be in a group defined by another app (before this had no implications).
7320                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7321                    p.group = mPermissionGroups.get(p.info.group);
7322                    // Warn for a permission in an unknown group.
7323                    if (p.info.group != null && p.group == null) {
7324                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7325                                + p.info.packageName + " in an unknown group " + p.info.group);
7326                    }
7327                }
7328
7329                ArrayMap<String, BasePermission> permissionMap =
7330                        p.tree ? mSettings.mPermissionTrees
7331                                : mSettings.mPermissions;
7332                BasePermission bp = permissionMap.get(p.info.name);
7333
7334                // Allow system apps to redefine non-system permissions
7335                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7336                    final boolean currentOwnerIsSystem = (bp.perm != null
7337                            && isSystemApp(bp.perm.owner));
7338                    if (isSystemApp(p.owner)) {
7339                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7340                            // It's a built-in permission and no owner, take ownership now
7341                            bp.packageSetting = pkgSetting;
7342                            bp.perm = p;
7343                            bp.uid = pkg.applicationInfo.uid;
7344                            bp.sourcePackage = p.info.packageName;
7345                        } else if (!currentOwnerIsSystem) {
7346                            String msg = "New decl " + p.owner + " of permission  "
7347                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7348                            reportSettingsProblem(Log.WARN, msg);
7349                            bp = null;
7350                        }
7351                    }
7352                }
7353
7354                if (bp == null) {
7355                    bp = new BasePermission(p.info.name, p.info.packageName,
7356                            BasePermission.TYPE_NORMAL);
7357                    permissionMap.put(p.info.name, bp);
7358                }
7359
7360                if (bp.perm == null) {
7361                    if (bp.sourcePackage == null
7362                            || bp.sourcePackage.equals(p.info.packageName)) {
7363                        BasePermission tree = findPermissionTreeLP(p.info.name);
7364                        if (tree == null
7365                                || tree.sourcePackage.equals(p.info.packageName)) {
7366                            bp.packageSetting = pkgSetting;
7367                            bp.perm = p;
7368                            bp.uid = pkg.applicationInfo.uid;
7369                            bp.sourcePackage = p.info.packageName;
7370                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7371                                if (r == null) {
7372                                    r = new StringBuilder(256);
7373                                } else {
7374                                    r.append(' ');
7375                                }
7376                                r.append(p.info.name);
7377                            }
7378                        } else {
7379                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7380                                    + p.info.packageName + " ignored: base tree "
7381                                    + tree.name + " is from package "
7382                                    + tree.sourcePackage);
7383                        }
7384                    } else {
7385                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7386                                + p.info.packageName + " ignored: original from "
7387                                + bp.sourcePackage);
7388                    }
7389                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7390                    if (r == null) {
7391                        r = new StringBuilder(256);
7392                    } else {
7393                        r.append(' ');
7394                    }
7395                    r.append("DUP:");
7396                    r.append(p.info.name);
7397                }
7398                if (bp.perm == p) {
7399                    bp.protectionLevel = p.info.protectionLevel;
7400                }
7401            }
7402
7403            if (r != null) {
7404                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7405            }
7406
7407            N = pkg.instrumentation.size();
7408            r = null;
7409            for (i=0; i<N; i++) {
7410                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7411                a.info.packageName = pkg.applicationInfo.packageName;
7412                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7413                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7414                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7415                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7416                a.info.dataDir = pkg.applicationInfo.dataDir;
7417
7418                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7419                // need other information about the application, like the ABI and what not ?
7420                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7421                mInstrumentation.put(a.getComponentName(), a);
7422                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7423                    if (r == null) {
7424                        r = new StringBuilder(256);
7425                    } else {
7426                        r.append(' ');
7427                    }
7428                    r.append(a.info.name);
7429                }
7430            }
7431            if (r != null) {
7432                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7433            }
7434
7435            if (pkg.protectedBroadcasts != null) {
7436                N = pkg.protectedBroadcasts.size();
7437                for (i=0; i<N; i++) {
7438                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7439                }
7440            }
7441
7442            pkgSetting.setTimeStamp(scanFileTime);
7443
7444            // Create idmap files for pairs of (packages, overlay packages).
7445            // Note: "android", ie framework-res.apk, is handled by native layers.
7446            if (pkg.mOverlayTarget != null) {
7447                // This is an overlay package.
7448                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7449                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7450                        mOverlays.put(pkg.mOverlayTarget,
7451                                new ArrayMap<String, PackageParser.Package>());
7452                    }
7453                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7454                    map.put(pkg.packageName, pkg);
7455                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7456                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7457                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7458                                "scanPackageLI failed to createIdmap");
7459                    }
7460                }
7461            } else if (mOverlays.containsKey(pkg.packageName) &&
7462                    !pkg.packageName.equals("android")) {
7463                // This is a regular package, with one or more known overlay packages.
7464                createIdmapsForPackageLI(pkg);
7465            }
7466        }
7467
7468        return pkg;
7469    }
7470
7471    /**
7472     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7473     * is derived purely on the basis of the contents of {@code scanFile} and
7474     * {@code cpuAbiOverride}.
7475     *
7476     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7477     */
7478    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7479                                 String cpuAbiOverride, boolean extractLibs)
7480            throws PackageManagerException {
7481        // TODO: We can probably be smarter about this stuff. For installed apps,
7482        // we can calculate this information at install time once and for all. For
7483        // system apps, we can probably assume that this information doesn't change
7484        // after the first boot scan. As things stand, we do lots of unnecessary work.
7485
7486        // Give ourselves some initial paths; we'll come back for another
7487        // pass once we've determined ABI below.
7488        setNativeLibraryPaths(pkg);
7489
7490        // We would never need to extract libs for forward-locked and external packages,
7491        // since the container service will do it for us. We shouldn't attempt to
7492        // extract libs from system app when it was not updated.
7493        if (pkg.isForwardLocked() || isExternal(pkg) ||
7494            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7495            extractLibs = false;
7496        }
7497
7498        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7499        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7500
7501        NativeLibraryHelper.Handle handle = null;
7502        try {
7503            handle = NativeLibraryHelper.Handle.create(scanFile);
7504            // TODO(multiArch): This can be null for apps that didn't go through the
7505            // usual installation process. We can calculate it again, like we
7506            // do during install time.
7507            //
7508            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7509            // unnecessary.
7510            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7511
7512            // Null out the abis so that they can be recalculated.
7513            pkg.applicationInfo.primaryCpuAbi = null;
7514            pkg.applicationInfo.secondaryCpuAbi = null;
7515            if (isMultiArch(pkg.applicationInfo)) {
7516                // Warn if we've set an abiOverride for multi-lib packages..
7517                // By definition, we need to copy both 32 and 64 bit libraries for
7518                // such packages.
7519                if (pkg.cpuAbiOverride != null
7520                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7521                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7522                }
7523
7524                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7525                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7526                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7527                    if (extractLibs) {
7528                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7529                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7530                                useIsaSpecificSubdirs);
7531                    } else {
7532                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7533                    }
7534                }
7535
7536                maybeThrowExceptionForMultiArchCopy(
7537                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7538
7539                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7540                    if (extractLibs) {
7541                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7542                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7543                                useIsaSpecificSubdirs);
7544                    } else {
7545                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7546                    }
7547                }
7548
7549                maybeThrowExceptionForMultiArchCopy(
7550                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7551
7552                if (abi64 >= 0) {
7553                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7554                }
7555
7556                if (abi32 >= 0) {
7557                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7558                    if (abi64 >= 0) {
7559                        pkg.applicationInfo.secondaryCpuAbi = abi;
7560                    } else {
7561                        pkg.applicationInfo.primaryCpuAbi = abi;
7562                    }
7563                }
7564            } else {
7565                String[] abiList = (cpuAbiOverride != null) ?
7566                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7567
7568                // Enable gross and lame hacks for apps that are built with old
7569                // SDK tools. We must scan their APKs for renderscript bitcode and
7570                // not launch them if it's present. Don't bother checking on devices
7571                // that don't have 64 bit support.
7572                boolean needsRenderScriptOverride = false;
7573                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7574                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7575                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7576                    needsRenderScriptOverride = true;
7577                }
7578
7579                final int copyRet;
7580                if (extractLibs) {
7581                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7582                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7583                } else {
7584                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7585                }
7586
7587                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7588                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7589                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7590                }
7591
7592                if (copyRet >= 0) {
7593                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7594                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7595                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7596                } else if (needsRenderScriptOverride) {
7597                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7598                }
7599            }
7600        } catch (IOException ioe) {
7601            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7602        } finally {
7603            IoUtils.closeQuietly(handle);
7604        }
7605
7606        // Now that we've calculated the ABIs and determined if it's an internal app,
7607        // we will go ahead and populate the nativeLibraryPath.
7608        setNativeLibraryPaths(pkg);
7609    }
7610
7611    /**
7612     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7613     * i.e, so that all packages can be run inside a single process if required.
7614     *
7615     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7616     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7617     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7618     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7619     * updating a package that belongs to a shared user.
7620     *
7621     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7622     * adds unnecessary complexity.
7623     */
7624    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7625            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7626        String requiredInstructionSet = null;
7627        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7628            requiredInstructionSet = VMRuntime.getInstructionSet(
7629                     scannedPackage.applicationInfo.primaryCpuAbi);
7630        }
7631
7632        PackageSetting requirer = null;
7633        for (PackageSetting ps : packagesForUser) {
7634            // If packagesForUser contains scannedPackage, we skip it. This will happen
7635            // when scannedPackage is an update of an existing package. Without this check,
7636            // we will never be able to change the ABI of any package belonging to a shared
7637            // user, even if it's compatible with other packages.
7638            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7639                if (ps.primaryCpuAbiString == null) {
7640                    continue;
7641                }
7642
7643                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7644                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7645                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7646                    // this but there's not much we can do.
7647                    String errorMessage = "Instruction set mismatch, "
7648                            + ((requirer == null) ? "[caller]" : requirer)
7649                            + " requires " + requiredInstructionSet + " whereas " + ps
7650                            + " requires " + instructionSet;
7651                    Slog.w(TAG, errorMessage);
7652                }
7653
7654                if (requiredInstructionSet == null) {
7655                    requiredInstructionSet = instructionSet;
7656                    requirer = ps;
7657                }
7658            }
7659        }
7660
7661        if (requiredInstructionSet != null) {
7662            String adjustedAbi;
7663            if (requirer != null) {
7664                // requirer != null implies that either scannedPackage was null or that scannedPackage
7665                // did not require an ABI, in which case we have to adjust scannedPackage to match
7666                // the ABI of the set (which is the same as requirer's ABI)
7667                adjustedAbi = requirer.primaryCpuAbiString;
7668                if (scannedPackage != null) {
7669                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7670                }
7671            } else {
7672                // requirer == null implies that we're updating all ABIs in the set to
7673                // match scannedPackage.
7674                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7675            }
7676
7677            for (PackageSetting ps : packagesForUser) {
7678                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7679                    if (ps.primaryCpuAbiString != null) {
7680                        continue;
7681                    }
7682
7683                    ps.primaryCpuAbiString = adjustedAbi;
7684                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7685                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7686                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7687
7688                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7689                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7690                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7691                            ps.primaryCpuAbiString = null;
7692                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7693                            return;
7694                        } else {
7695                            mInstaller.rmdex(ps.codePathString,
7696                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7697                        }
7698                    }
7699                }
7700            }
7701        }
7702    }
7703
7704    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7705        synchronized (mPackages) {
7706            mResolverReplaced = true;
7707            // Set up information for custom user intent resolution activity.
7708            mResolveActivity.applicationInfo = pkg.applicationInfo;
7709            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7710            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7711            mResolveActivity.processName = pkg.applicationInfo.packageName;
7712            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7713            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7714                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7715            mResolveActivity.theme = 0;
7716            mResolveActivity.exported = true;
7717            mResolveActivity.enabled = true;
7718            mResolveInfo.activityInfo = mResolveActivity;
7719            mResolveInfo.priority = 0;
7720            mResolveInfo.preferredOrder = 0;
7721            mResolveInfo.match = 0;
7722            mResolveComponentName = mCustomResolverComponentName;
7723            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7724                    mResolveComponentName);
7725        }
7726    }
7727
7728    private static String calculateBundledApkRoot(final String codePathString) {
7729        final File codePath = new File(codePathString);
7730        final File codeRoot;
7731        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7732            codeRoot = Environment.getRootDirectory();
7733        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7734            codeRoot = Environment.getOemDirectory();
7735        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7736            codeRoot = Environment.getVendorDirectory();
7737        } else {
7738            // Unrecognized code path; take its top real segment as the apk root:
7739            // e.g. /something/app/blah.apk => /something
7740            try {
7741                File f = codePath.getCanonicalFile();
7742                File parent = f.getParentFile();    // non-null because codePath is a file
7743                File tmp;
7744                while ((tmp = parent.getParentFile()) != null) {
7745                    f = parent;
7746                    parent = tmp;
7747                }
7748                codeRoot = f;
7749                Slog.w(TAG, "Unrecognized code path "
7750                        + codePath + " - using " + codeRoot);
7751            } catch (IOException e) {
7752                // Can't canonicalize the code path -- shenanigans?
7753                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7754                return Environment.getRootDirectory().getPath();
7755            }
7756        }
7757        return codeRoot.getPath();
7758    }
7759
7760    /**
7761     * Derive and set the location of native libraries for the given package,
7762     * which varies depending on where and how the package was installed.
7763     */
7764    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7765        final ApplicationInfo info = pkg.applicationInfo;
7766        final String codePath = pkg.codePath;
7767        final File codeFile = new File(codePath);
7768        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7769        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7770
7771        info.nativeLibraryRootDir = null;
7772        info.nativeLibraryRootRequiresIsa = false;
7773        info.nativeLibraryDir = null;
7774        info.secondaryNativeLibraryDir = null;
7775
7776        if (isApkFile(codeFile)) {
7777            // Monolithic install
7778            if (bundledApp) {
7779                // If "/system/lib64/apkname" exists, assume that is the per-package
7780                // native library directory to use; otherwise use "/system/lib/apkname".
7781                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7782                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7783                        getPrimaryInstructionSet(info));
7784
7785                // This is a bundled system app so choose the path based on the ABI.
7786                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7787                // is just the default path.
7788                final String apkName = deriveCodePathName(codePath);
7789                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7790                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7791                        apkName).getAbsolutePath();
7792
7793                if (info.secondaryCpuAbi != null) {
7794                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7795                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7796                            secondaryLibDir, apkName).getAbsolutePath();
7797                }
7798            } else if (asecApp) {
7799                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7800                        .getAbsolutePath();
7801            } else {
7802                final String apkName = deriveCodePathName(codePath);
7803                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7804                        .getAbsolutePath();
7805            }
7806
7807            info.nativeLibraryRootRequiresIsa = false;
7808            info.nativeLibraryDir = info.nativeLibraryRootDir;
7809        } else {
7810            // Cluster install
7811            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7812            info.nativeLibraryRootRequiresIsa = true;
7813
7814            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7815                    getPrimaryInstructionSet(info)).getAbsolutePath();
7816
7817            if (info.secondaryCpuAbi != null) {
7818                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7819                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7820            }
7821        }
7822    }
7823
7824    /**
7825     * Calculate the abis and roots for a bundled app. These can uniquely
7826     * be determined from the contents of the system partition, i.e whether
7827     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7828     * of this information, and instead assume that the system was built
7829     * sensibly.
7830     */
7831    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7832                                           PackageSetting pkgSetting) {
7833        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7834
7835        // If "/system/lib64/apkname" exists, assume that is the per-package
7836        // native library directory to use; otherwise use "/system/lib/apkname".
7837        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7838        setBundledAppAbi(pkg, apkRoot, apkName);
7839        // pkgSetting might be null during rescan following uninstall of updates
7840        // to a bundled app, so accommodate that possibility.  The settings in
7841        // that case will be established later from the parsed package.
7842        //
7843        // If the settings aren't null, sync them up with what we've just derived.
7844        // note that apkRoot isn't stored in the package settings.
7845        if (pkgSetting != null) {
7846            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7847            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7848        }
7849    }
7850
7851    /**
7852     * Deduces the ABI of a bundled app and sets the relevant fields on the
7853     * parsed pkg object.
7854     *
7855     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7856     *        under which system libraries are installed.
7857     * @param apkName the name of the installed package.
7858     */
7859    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7860        final File codeFile = new File(pkg.codePath);
7861
7862        final boolean has64BitLibs;
7863        final boolean has32BitLibs;
7864        if (isApkFile(codeFile)) {
7865            // Monolithic install
7866            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7867            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7868        } else {
7869            // Cluster install
7870            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7871            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7872                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7873                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7874                has64BitLibs = (new File(rootDir, isa)).exists();
7875            } else {
7876                has64BitLibs = false;
7877            }
7878            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7879                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7880                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7881                has32BitLibs = (new File(rootDir, isa)).exists();
7882            } else {
7883                has32BitLibs = false;
7884            }
7885        }
7886
7887        if (has64BitLibs && !has32BitLibs) {
7888            // The package has 64 bit libs, but not 32 bit libs. Its primary
7889            // ABI should be 64 bit. We can safely assume here that the bundled
7890            // native libraries correspond to the most preferred ABI in the list.
7891
7892            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7893            pkg.applicationInfo.secondaryCpuAbi = null;
7894        } else if (has32BitLibs && !has64BitLibs) {
7895            // The package has 32 bit libs but not 64 bit libs. Its primary
7896            // ABI should be 32 bit.
7897
7898            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7899            pkg.applicationInfo.secondaryCpuAbi = null;
7900        } else if (has32BitLibs && has64BitLibs) {
7901            // The application has both 64 and 32 bit bundled libraries. We check
7902            // here that the app declares multiArch support, and warn if it doesn't.
7903            //
7904            // We will be lenient here and record both ABIs. The primary will be the
7905            // ABI that's higher on the list, i.e, a device that's configured to prefer
7906            // 64 bit apps will see a 64 bit primary ABI,
7907
7908            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7909                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7910            }
7911
7912            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7913                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7914                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7915            } else {
7916                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7917                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7918            }
7919        } else {
7920            pkg.applicationInfo.primaryCpuAbi = null;
7921            pkg.applicationInfo.secondaryCpuAbi = null;
7922        }
7923    }
7924
7925    private void killApplication(String pkgName, int appId, String reason) {
7926        // Request the ActivityManager to kill the process(only for existing packages)
7927        // so that we do not end up in a confused state while the user is still using the older
7928        // version of the application while the new one gets installed.
7929        IActivityManager am = ActivityManagerNative.getDefault();
7930        if (am != null) {
7931            try {
7932                am.killApplicationWithAppId(pkgName, appId, reason);
7933            } catch (RemoteException e) {
7934            }
7935        }
7936    }
7937
7938    void removePackageLI(PackageSetting ps, boolean chatty) {
7939        if (DEBUG_INSTALL) {
7940            if (chatty)
7941                Log.d(TAG, "Removing package " + ps.name);
7942        }
7943
7944        // writer
7945        synchronized (mPackages) {
7946            mPackages.remove(ps.name);
7947            final PackageParser.Package pkg = ps.pkg;
7948            if (pkg != null) {
7949                cleanPackageDataStructuresLILPw(pkg, chatty);
7950            }
7951        }
7952    }
7953
7954    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7955        if (DEBUG_INSTALL) {
7956            if (chatty)
7957                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7958        }
7959
7960        // writer
7961        synchronized (mPackages) {
7962            mPackages.remove(pkg.applicationInfo.packageName);
7963            cleanPackageDataStructuresLILPw(pkg, chatty);
7964        }
7965    }
7966
7967    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7968        int N = pkg.providers.size();
7969        StringBuilder r = null;
7970        int i;
7971        for (i=0; i<N; i++) {
7972            PackageParser.Provider p = pkg.providers.get(i);
7973            mProviders.removeProvider(p);
7974            if (p.info.authority == null) {
7975
7976                /* There was another ContentProvider with this authority when
7977                 * this app was installed so this authority is null,
7978                 * Ignore it as we don't have to unregister the provider.
7979                 */
7980                continue;
7981            }
7982            String names[] = p.info.authority.split(";");
7983            for (int j = 0; j < names.length; j++) {
7984                if (mProvidersByAuthority.get(names[j]) == p) {
7985                    mProvidersByAuthority.remove(names[j]);
7986                    if (DEBUG_REMOVE) {
7987                        if (chatty)
7988                            Log.d(TAG, "Unregistered content provider: " + names[j]
7989                                    + ", className = " + p.info.name + ", isSyncable = "
7990                                    + p.info.isSyncable);
7991                    }
7992                }
7993            }
7994            if (DEBUG_REMOVE && chatty) {
7995                if (r == null) {
7996                    r = new StringBuilder(256);
7997                } else {
7998                    r.append(' ');
7999                }
8000                r.append(p.info.name);
8001            }
8002        }
8003        if (r != null) {
8004            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8005        }
8006
8007        N = pkg.services.size();
8008        r = null;
8009        for (i=0; i<N; i++) {
8010            PackageParser.Service s = pkg.services.get(i);
8011            mServices.removeService(s);
8012            if (chatty) {
8013                if (r == null) {
8014                    r = new StringBuilder(256);
8015                } else {
8016                    r.append(' ');
8017                }
8018                r.append(s.info.name);
8019            }
8020        }
8021        if (r != null) {
8022            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8023        }
8024
8025        N = pkg.receivers.size();
8026        r = null;
8027        for (i=0; i<N; i++) {
8028            PackageParser.Activity a = pkg.receivers.get(i);
8029            mReceivers.removeActivity(a, "receiver");
8030            if (DEBUG_REMOVE && chatty) {
8031                if (r == null) {
8032                    r = new StringBuilder(256);
8033                } else {
8034                    r.append(' ');
8035                }
8036                r.append(a.info.name);
8037            }
8038        }
8039        if (r != null) {
8040            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8041        }
8042
8043        N = pkg.activities.size();
8044        r = null;
8045        for (i=0; i<N; i++) {
8046            PackageParser.Activity a = pkg.activities.get(i);
8047            mActivities.removeActivity(a, "activity");
8048            if (DEBUG_REMOVE && chatty) {
8049                if (r == null) {
8050                    r = new StringBuilder(256);
8051                } else {
8052                    r.append(' ');
8053                }
8054                r.append(a.info.name);
8055            }
8056        }
8057        if (r != null) {
8058            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8059        }
8060
8061        N = pkg.permissions.size();
8062        r = null;
8063        for (i=0; i<N; i++) {
8064            PackageParser.Permission p = pkg.permissions.get(i);
8065            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8066            if (bp == null) {
8067                bp = mSettings.mPermissionTrees.get(p.info.name);
8068            }
8069            if (bp != null && bp.perm == p) {
8070                bp.perm = null;
8071                if (DEBUG_REMOVE && chatty) {
8072                    if (r == null) {
8073                        r = new StringBuilder(256);
8074                    } else {
8075                        r.append(' ');
8076                    }
8077                    r.append(p.info.name);
8078                }
8079            }
8080            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8081                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8082                if (appOpPerms != null) {
8083                    appOpPerms.remove(pkg.packageName);
8084                }
8085            }
8086        }
8087        if (r != null) {
8088            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8089        }
8090
8091        N = pkg.requestedPermissions.size();
8092        r = null;
8093        for (i=0; i<N; i++) {
8094            String perm = pkg.requestedPermissions.get(i);
8095            BasePermission bp = mSettings.mPermissions.get(perm);
8096            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8097                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8098                if (appOpPerms != null) {
8099                    appOpPerms.remove(pkg.packageName);
8100                    if (appOpPerms.isEmpty()) {
8101                        mAppOpPermissionPackages.remove(perm);
8102                    }
8103                }
8104            }
8105        }
8106        if (r != null) {
8107            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8108        }
8109
8110        N = pkg.instrumentation.size();
8111        r = null;
8112        for (i=0; i<N; i++) {
8113            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8114            mInstrumentation.remove(a.getComponentName());
8115            if (DEBUG_REMOVE && chatty) {
8116                if (r == null) {
8117                    r = new StringBuilder(256);
8118                } else {
8119                    r.append(' ');
8120                }
8121                r.append(a.info.name);
8122            }
8123        }
8124        if (r != null) {
8125            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8126        }
8127
8128        r = null;
8129        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8130            // Only system apps can hold shared libraries.
8131            if (pkg.libraryNames != null) {
8132                for (i=0; i<pkg.libraryNames.size(); i++) {
8133                    String name = pkg.libraryNames.get(i);
8134                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8135                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8136                        mSharedLibraries.remove(name);
8137                        if (DEBUG_REMOVE && chatty) {
8138                            if (r == null) {
8139                                r = new StringBuilder(256);
8140                            } else {
8141                                r.append(' ');
8142                            }
8143                            r.append(name);
8144                        }
8145                    }
8146                }
8147            }
8148        }
8149        if (r != null) {
8150            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8151        }
8152    }
8153
8154    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8155        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8156            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8157                return true;
8158            }
8159        }
8160        return false;
8161    }
8162
8163    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8164    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8165    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8166
8167    private void updatePermissionsLPw(String changingPkg,
8168            PackageParser.Package pkgInfo, int flags) {
8169        // Make sure there are no dangling permission trees.
8170        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8171        while (it.hasNext()) {
8172            final BasePermission bp = it.next();
8173            if (bp.packageSetting == null) {
8174                // We may not yet have parsed the package, so just see if
8175                // we still know about its settings.
8176                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8177            }
8178            if (bp.packageSetting == null) {
8179                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8180                        + " from package " + bp.sourcePackage);
8181                it.remove();
8182            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8183                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8184                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8185                            + " from package " + bp.sourcePackage);
8186                    flags |= UPDATE_PERMISSIONS_ALL;
8187                    it.remove();
8188                }
8189            }
8190        }
8191
8192        // Make sure all dynamic permissions have been assigned to a package,
8193        // and make sure there are no dangling permissions.
8194        it = mSettings.mPermissions.values().iterator();
8195        while (it.hasNext()) {
8196            final BasePermission bp = it.next();
8197            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8198                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8199                        + bp.name + " pkg=" + bp.sourcePackage
8200                        + " info=" + bp.pendingInfo);
8201                if (bp.packageSetting == null && bp.pendingInfo != null) {
8202                    final BasePermission tree = findPermissionTreeLP(bp.name);
8203                    if (tree != null && tree.perm != null) {
8204                        bp.packageSetting = tree.packageSetting;
8205                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8206                                new PermissionInfo(bp.pendingInfo));
8207                        bp.perm.info.packageName = tree.perm.info.packageName;
8208                        bp.perm.info.name = bp.name;
8209                        bp.uid = tree.uid;
8210                    }
8211                }
8212            }
8213            if (bp.packageSetting == null) {
8214                // We may not yet have parsed the package, so just see if
8215                // we still know about its settings.
8216                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8217            }
8218            if (bp.packageSetting == null) {
8219                Slog.w(TAG, "Removing dangling permission: " + bp.name
8220                        + " from package " + bp.sourcePackage);
8221                it.remove();
8222            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8223                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8224                    Slog.i(TAG, "Removing old permission: " + bp.name
8225                            + " from package " + bp.sourcePackage);
8226                    flags |= UPDATE_PERMISSIONS_ALL;
8227                    it.remove();
8228                }
8229            }
8230        }
8231
8232        // Now update the permissions for all packages, in particular
8233        // replace the granted permissions of the system packages.
8234        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8235            for (PackageParser.Package pkg : mPackages.values()) {
8236                if (pkg != pkgInfo) {
8237                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8238                            changingPkg);
8239                }
8240            }
8241        }
8242
8243        if (pkgInfo != null) {
8244            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8245        }
8246    }
8247
8248    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8249            String packageOfInterest) {
8250        // IMPORTANT: There are two types of permissions: install and runtime.
8251        // Install time permissions are granted when the app is installed to
8252        // all device users and users added in the future. Runtime permissions
8253        // are granted at runtime explicitly to specific users. Normal and signature
8254        // protected permissions are install time permissions. Dangerous permissions
8255        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8256        // otherwise they are runtime permissions. This function does not manage
8257        // runtime permissions except for the case an app targeting Lollipop MR1
8258        // being upgraded to target a newer SDK, in which case dangerous permissions
8259        // are transformed from install time to runtime ones.
8260
8261        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8262        if (ps == null) {
8263            return;
8264        }
8265
8266        PermissionsState permissionsState = ps.getPermissionsState();
8267        PermissionsState origPermissions = permissionsState;
8268
8269        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8270
8271        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8272
8273        boolean changedInstallPermission = false;
8274
8275        if (replace) {
8276            ps.installPermissionsFixed = false;
8277            if (!ps.isSharedUser()) {
8278                origPermissions = new PermissionsState(permissionsState);
8279                permissionsState.reset();
8280            }
8281        }
8282
8283        permissionsState.setGlobalGids(mGlobalGids);
8284
8285        final int N = pkg.requestedPermissions.size();
8286        for (int i=0; i<N; i++) {
8287            final String name = pkg.requestedPermissions.get(i);
8288            final BasePermission bp = mSettings.mPermissions.get(name);
8289
8290            if (DEBUG_INSTALL) {
8291                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8292            }
8293
8294            if (bp == null || bp.packageSetting == null) {
8295                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8296                    Slog.w(TAG, "Unknown permission " + name
8297                            + " in package " + pkg.packageName);
8298                }
8299                continue;
8300            }
8301
8302            final String perm = bp.name;
8303            boolean allowedSig = false;
8304            int grant = GRANT_DENIED;
8305
8306            // Keep track of app op permissions.
8307            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8308                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8309                if (pkgs == null) {
8310                    pkgs = new ArraySet<>();
8311                    mAppOpPermissionPackages.put(bp.name, pkgs);
8312                }
8313                pkgs.add(pkg.packageName);
8314            }
8315
8316            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8317            switch (level) {
8318                case PermissionInfo.PROTECTION_NORMAL: {
8319                    // For all apps normal permissions are install time ones.
8320                    grant = GRANT_INSTALL;
8321                } break;
8322
8323                case PermissionInfo.PROTECTION_DANGEROUS: {
8324                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8325                        // For legacy apps dangerous permissions are install time ones.
8326                        grant = GRANT_INSTALL_LEGACY;
8327                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8328                        // For legacy apps that became modern, install becomes runtime.
8329                        grant = GRANT_UPGRADE;
8330                    } else {
8331                        // For modern apps keep runtime permissions unchanged.
8332                        grant = GRANT_RUNTIME;
8333                    }
8334                } break;
8335
8336                case PermissionInfo.PROTECTION_SIGNATURE: {
8337                    // For all apps signature permissions are install time ones.
8338                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8339                    if (allowedSig) {
8340                        grant = GRANT_INSTALL;
8341                    }
8342                } break;
8343            }
8344
8345            if (DEBUG_INSTALL) {
8346                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8347            }
8348
8349            if (grant != GRANT_DENIED) {
8350                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8351                    // If this is an existing, non-system package, then
8352                    // we can't add any new permissions to it.
8353                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8354                        // Except...  if this is a permission that was added
8355                        // to the platform (note: need to only do this when
8356                        // updating the platform).
8357                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8358                            grant = GRANT_DENIED;
8359                        }
8360                    }
8361                }
8362
8363                switch (grant) {
8364                    case GRANT_INSTALL: {
8365                        // Revoke this as runtime permission to handle the case of
8366                        // a runtime permission being downgraded to an install one.
8367                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8368                            if (origPermissions.getRuntimePermissionState(
8369                                    bp.name, userId) != null) {
8370                                // Revoke the runtime permission and clear the flags.
8371                                origPermissions.revokeRuntimePermission(bp, userId);
8372                                origPermissions.updatePermissionFlags(bp, userId,
8373                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8374                                // If we revoked a permission permission, we have to write.
8375                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8376                                        changedRuntimePermissionUserIds, userId);
8377                            }
8378                        }
8379                        // Grant an install permission.
8380                        if (permissionsState.grantInstallPermission(bp) !=
8381                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8382                            changedInstallPermission = true;
8383                        }
8384                    } break;
8385
8386                    case GRANT_INSTALL_LEGACY: {
8387                        // Grant an install permission.
8388                        if (permissionsState.grantInstallPermission(bp) !=
8389                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8390                            changedInstallPermission = true;
8391                        }
8392                    } break;
8393
8394                    case GRANT_RUNTIME: {
8395                        // Grant previously granted runtime permissions.
8396                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8397                            PermissionState permissionState = origPermissions
8398                                    .getRuntimePermissionState(bp.name, userId);
8399                            final int flags = permissionState != null
8400                                    ? permissionState.getFlags() : 0;
8401                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8402                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8403                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8404                                    // If we cannot put the permission as it was, we have to write.
8405                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8406                                            changedRuntimePermissionUserIds, userId);
8407                                }
8408                            }
8409                            // Propagate the permission flags.
8410                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8411                        }
8412                    } break;
8413
8414                    case GRANT_UPGRADE: {
8415                        // Grant runtime permissions for a previously held install permission.
8416                        PermissionState permissionState = origPermissions
8417                                .getInstallPermissionState(bp.name);
8418                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8419
8420                        if (origPermissions.revokeInstallPermission(bp)
8421                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8422                            // We will be transferring the permission flags, so clear them.
8423                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8424                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8425                            changedInstallPermission = true;
8426                        }
8427
8428                        // If the permission is not to be promoted to runtime we ignore it and
8429                        // also its other flags as they are not applicable to install permissions.
8430                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8431                            for (int userId : currentUserIds) {
8432                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8433                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8434                                    // Transfer the permission flags.
8435                                    permissionsState.updatePermissionFlags(bp, userId,
8436                                            flags, flags);
8437                                    // If we granted the permission, we have to write.
8438                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8439                                            changedRuntimePermissionUserIds, userId);
8440                                }
8441                            }
8442                        }
8443                    } break;
8444
8445                    default: {
8446                        if (packageOfInterest == null
8447                                || packageOfInterest.equals(pkg.packageName)) {
8448                            Slog.w(TAG, "Not granting permission " + perm
8449                                    + " to package " + pkg.packageName
8450                                    + " because it was previously installed without");
8451                        }
8452                    } break;
8453                }
8454            } else {
8455                if (permissionsState.revokeInstallPermission(bp) !=
8456                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8457                    // Also drop the permission flags.
8458                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8459                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8460                    changedInstallPermission = true;
8461                    Slog.i(TAG, "Un-granting permission " + perm
8462                            + " from package " + pkg.packageName
8463                            + " (protectionLevel=" + bp.protectionLevel
8464                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8465                            + ")");
8466                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8467                    // Don't print warning for app op permissions, since it is fine for them
8468                    // not to be granted, there is a UI for the user to decide.
8469                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8470                        Slog.w(TAG, "Not granting permission " + perm
8471                                + " to package " + pkg.packageName
8472                                + " (protectionLevel=" + bp.protectionLevel
8473                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8474                                + ")");
8475                    }
8476                }
8477            }
8478        }
8479
8480        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8481                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8482            // This is the first that we have heard about this package, so the
8483            // permissions we have now selected are fixed until explicitly
8484            // changed.
8485            ps.installPermissionsFixed = true;
8486        }
8487
8488        // Persist the runtime permissions state for users with changes.
8489        for (int userId : changedRuntimePermissionUserIds) {
8490            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8491        }
8492    }
8493
8494    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8495        boolean allowed = false;
8496        final int NP = PackageParser.NEW_PERMISSIONS.length;
8497        for (int ip=0; ip<NP; ip++) {
8498            final PackageParser.NewPermissionInfo npi
8499                    = PackageParser.NEW_PERMISSIONS[ip];
8500            if (npi.name.equals(perm)
8501                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8502                allowed = true;
8503                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8504                        + pkg.packageName);
8505                break;
8506            }
8507        }
8508        return allowed;
8509    }
8510
8511    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8512            BasePermission bp, PermissionsState origPermissions) {
8513        boolean allowed;
8514        allowed = (compareSignatures(
8515                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8516                        == PackageManager.SIGNATURE_MATCH)
8517                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8518                        == PackageManager.SIGNATURE_MATCH);
8519        if (!allowed && (bp.protectionLevel
8520                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8521            if (isSystemApp(pkg)) {
8522                // For updated system applications, a system permission
8523                // is granted only if it had been defined by the original application.
8524                if (pkg.isUpdatedSystemApp()) {
8525                    final PackageSetting sysPs = mSettings
8526                            .getDisabledSystemPkgLPr(pkg.packageName);
8527                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8528                        // If the original was granted this permission, we take
8529                        // that grant decision as read and propagate it to the
8530                        // update.
8531                        if (sysPs.isPrivileged()) {
8532                            allowed = true;
8533                        }
8534                    } else {
8535                        // The system apk may have been updated with an older
8536                        // version of the one on the data partition, but which
8537                        // granted a new system permission that it didn't have
8538                        // before.  In this case we do want to allow the app to
8539                        // now get the new permission if the ancestral apk is
8540                        // privileged to get it.
8541                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8542                            for (int j=0;
8543                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8544                                if (perm.equals(
8545                                        sysPs.pkg.requestedPermissions.get(j))) {
8546                                    allowed = true;
8547                                    break;
8548                                }
8549                            }
8550                        }
8551                    }
8552                } else {
8553                    allowed = isPrivilegedApp(pkg);
8554                }
8555            }
8556        }
8557        if (!allowed) {
8558            if (!allowed && (bp.protectionLevel
8559                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8560                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8561                // If this was a previously normal/dangerous permission that got moved
8562                // to a system permission as part of the runtime permission redesign, then
8563                // we still want to blindly grant it to old apps.
8564                allowed = true;
8565            }
8566            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8567                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8568                // If this permission is to be granted to the system installer and
8569                // this app is an installer, then it gets the permission.
8570                allowed = true;
8571            }
8572            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8573                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8574                // If this permission is to be granted to the system verifier and
8575                // this app is a verifier, then it gets the permission.
8576                allowed = true;
8577            }
8578            if (!allowed && (bp.protectionLevel
8579                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8580                    && isSystemApp(pkg)) {
8581                // Any pre-installed system app is allowed to get this permission.
8582                allowed = true;
8583            }
8584            if (!allowed && (bp.protectionLevel
8585                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8586                // For development permissions, a development permission
8587                // is granted only if it was already granted.
8588                allowed = origPermissions.hasInstallPermission(perm);
8589            }
8590        }
8591        return allowed;
8592    }
8593
8594    final class ActivityIntentResolver
8595            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8596        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8597                boolean defaultOnly, int userId) {
8598            if (!sUserManager.exists(userId)) return null;
8599            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8600            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8601        }
8602
8603        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8604                int userId) {
8605            if (!sUserManager.exists(userId)) return null;
8606            mFlags = flags;
8607            return super.queryIntent(intent, resolvedType,
8608                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8609        }
8610
8611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8612                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8613            if (!sUserManager.exists(userId)) return null;
8614            if (packageActivities == null) {
8615                return null;
8616            }
8617            mFlags = flags;
8618            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8619            final int N = packageActivities.size();
8620            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8621                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8622
8623            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8624            for (int i = 0; i < N; ++i) {
8625                intentFilters = packageActivities.get(i).intents;
8626                if (intentFilters != null && intentFilters.size() > 0) {
8627                    PackageParser.ActivityIntentInfo[] array =
8628                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8629                    intentFilters.toArray(array);
8630                    listCut.add(array);
8631                }
8632            }
8633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8634        }
8635
8636        public final void addActivity(PackageParser.Activity a, String type) {
8637            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8638            mActivities.put(a.getComponentName(), a);
8639            if (DEBUG_SHOW_INFO)
8640                Log.v(
8641                TAG, "  " + type + " " +
8642                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8643            if (DEBUG_SHOW_INFO)
8644                Log.v(TAG, "    Class=" + a.info.name);
8645            final int NI = a.intents.size();
8646            for (int j=0; j<NI; j++) {
8647                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8648                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8649                    intent.setPriority(0);
8650                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8651                            + a.className + " with priority > 0, forcing to 0");
8652                }
8653                if (DEBUG_SHOW_INFO) {
8654                    Log.v(TAG, "    IntentFilter:");
8655                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8656                }
8657                if (!intent.debugCheck()) {
8658                    Log.w(TAG, "==> For Activity " + a.info.name);
8659                }
8660                addFilter(intent);
8661            }
8662        }
8663
8664        public final void removeActivity(PackageParser.Activity a, String type) {
8665            mActivities.remove(a.getComponentName());
8666            if (DEBUG_SHOW_INFO) {
8667                Log.v(TAG, "  " + type + " "
8668                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8669                                : a.info.name) + ":");
8670                Log.v(TAG, "    Class=" + a.info.name);
8671            }
8672            final int NI = a.intents.size();
8673            for (int j=0; j<NI; j++) {
8674                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8675                if (DEBUG_SHOW_INFO) {
8676                    Log.v(TAG, "    IntentFilter:");
8677                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8678                }
8679                removeFilter(intent);
8680            }
8681        }
8682
8683        @Override
8684        protected boolean allowFilterResult(
8685                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8686            ActivityInfo filterAi = filter.activity.info;
8687            for (int i=dest.size()-1; i>=0; i--) {
8688                ActivityInfo destAi = dest.get(i).activityInfo;
8689                if (destAi.name == filterAi.name
8690                        && destAi.packageName == filterAi.packageName) {
8691                    return false;
8692                }
8693            }
8694            return true;
8695        }
8696
8697        @Override
8698        protected ActivityIntentInfo[] newArray(int size) {
8699            return new ActivityIntentInfo[size];
8700        }
8701
8702        @Override
8703        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8704            if (!sUserManager.exists(userId)) return true;
8705            PackageParser.Package p = filter.activity.owner;
8706            if (p != null) {
8707                PackageSetting ps = (PackageSetting)p.mExtras;
8708                if (ps != null) {
8709                    // System apps are never considered stopped for purposes of
8710                    // filtering, because there may be no way for the user to
8711                    // actually re-launch them.
8712                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8713                            && ps.getStopped(userId);
8714                }
8715            }
8716            return false;
8717        }
8718
8719        @Override
8720        protected boolean isPackageForFilter(String packageName,
8721                PackageParser.ActivityIntentInfo info) {
8722            return packageName.equals(info.activity.owner.packageName);
8723        }
8724
8725        @Override
8726        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8727                int match, int userId) {
8728            if (!sUserManager.exists(userId)) return null;
8729            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8730                return null;
8731            }
8732            final PackageParser.Activity activity = info.activity;
8733            if (mSafeMode && (activity.info.applicationInfo.flags
8734                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8735                return null;
8736            }
8737            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8738            if (ps == null) {
8739                return null;
8740            }
8741            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8742                    ps.readUserState(userId), userId);
8743            if (ai == null) {
8744                return null;
8745            }
8746            final ResolveInfo res = new ResolveInfo();
8747            res.activityInfo = ai;
8748            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8749                res.filter = info;
8750            }
8751            if (info != null) {
8752                res.handleAllWebDataURI = info.handleAllWebDataURI();
8753            }
8754            res.priority = info.getPriority();
8755            res.preferredOrder = activity.owner.mPreferredOrder;
8756            //System.out.println("Result: " + res.activityInfo.className +
8757            //                   " = " + res.priority);
8758            res.match = match;
8759            res.isDefault = info.hasDefault;
8760            res.labelRes = info.labelRes;
8761            res.nonLocalizedLabel = info.nonLocalizedLabel;
8762            if (userNeedsBadging(userId)) {
8763                res.noResourceId = true;
8764            } else {
8765                res.icon = info.icon;
8766            }
8767            res.iconResourceId = info.icon;
8768            res.system = res.activityInfo.applicationInfo.isSystemApp();
8769            return res;
8770        }
8771
8772        @Override
8773        protected void sortResults(List<ResolveInfo> results) {
8774            Collections.sort(results, mResolvePrioritySorter);
8775        }
8776
8777        @Override
8778        protected void dumpFilter(PrintWriter out, String prefix,
8779                PackageParser.ActivityIntentInfo filter) {
8780            out.print(prefix); out.print(
8781                    Integer.toHexString(System.identityHashCode(filter.activity)));
8782                    out.print(' ');
8783                    filter.activity.printComponentShortName(out);
8784                    out.print(" filter ");
8785                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8786        }
8787
8788        @Override
8789        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8790            return filter.activity;
8791        }
8792
8793        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8794            PackageParser.Activity activity = (PackageParser.Activity)label;
8795            out.print(prefix); out.print(
8796                    Integer.toHexString(System.identityHashCode(activity)));
8797                    out.print(' ');
8798                    activity.printComponentShortName(out);
8799            if (count > 1) {
8800                out.print(" ("); out.print(count); out.print(" filters)");
8801            }
8802            out.println();
8803        }
8804
8805//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8806//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8807//            final List<ResolveInfo> retList = Lists.newArrayList();
8808//            while (i.hasNext()) {
8809//                final ResolveInfo resolveInfo = i.next();
8810//                if (isEnabledLP(resolveInfo.activityInfo)) {
8811//                    retList.add(resolveInfo);
8812//                }
8813//            }
8814//            return retList;
8815//        }
8816
8817        // Keys are String (activity class name), values are Activity.
8818        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8819                = new ArrayMap<ComponentName, PackageParser.Activity>();
8820        private int mFlags;
8821    }
8822
8823    private final class ServiceIntentResolver
8824            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8825        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8826                boolean defaultOnly, int userId) {
8827            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8828            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8829        }
8830
8831        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8832                int userId) {
8833            if (!sUserManager.exists(userId)) return null;
8834            mFlags = flags;
8835            return super.queryIntent(intent, resolvedType,
8836                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8837        }
8838
8839        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8840                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8841            if (!sUserManager.exists(userId)) return null;
8842            if (packageServices == null) {
8843                return null;
8844            }
8845            mFlags = flags;
8846            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8847            final int N = packageServices.size();
8848            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8849                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8850
8851            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8852            for (int i = 0; i < N; ++i) {
8853                intentFilters = packageServices.get(i).intents;
8854                if (intentFilters != null && intentFilters.size() > 0) {
8855                    PackageParser.ServiceIntentInfo[] array =
8856                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8857                    intentFilters.toArray(array);
8858                    listCut.add(array);
8859                }
8860            }
8861            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8862        }
8863
8864        public final void addService(PackageParser.Service s) {
8865            mServices.put(s.getComponentName(), s);
8866            if (DEBUG_SHOW_INFO) {
8867                Log.v(TAG, "  "
8868                        + (s.info.nonLocalizedLabel != null
8869                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8870                Log.v(TAG, "    Class=" + s.info.name);
8871            }
8872            final int NI = s.intents.size();
8873            int j;
8874            for (j=0; j<NI; j++) {
8875                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8876                if (DEBUG_SHOW_INFO) {
8877                    Log.v(TAG, "    IntentFilter:");
8878                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8879                }
8880                if (!intent.debugCheck()) {
8881                    Log.w(TAG, "==> For Service " + s.info.name);
8882                }
8883                addFilter(intent);
8884            }
8885        }
8886
8887        public final void removeService(PackageParser.Service s) {
8888            mServices.remove(s.getComponentName());
8889            if (DEBUG_SHOW_INFO) {
8890                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8891                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8892                Log.v(TAG, "    Class=" + s.info.name);
8893            }
8894            final int NI = s.intents.size();
8895            int j;
8896            for (j=0; j<NI; j++) {
8897                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8898                if (DEBUG_SHOW_INFO) {
8899                    Log.v(TAG, "    IntentFilter:");
8900                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8901                }
8902                removeFilter(intent);
8903            }
8904        }
8905
8906        @Override
8907        protected boolean allowFilterResult(
8908                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8909            ServiceInfo filterSi = filter.service.info;
8910            for (int i=dest.size()-1; i>=0; i--) {
8911                ServiceInfo destAi = dest.get(i).serviceInfo;
8912                if (destAi.name == filterSi.name
8913                        && destAi.packageName == filterSi.packageName) {
8914                    return false;
8915                }
8916            }
8917            return true;
8918        }
8919
8920        @Override
8921        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8922            return new PackageParser.ServiceIntentInfo[size];
8923        }
8924
8925        @Override
8926        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8927            if (!sUserManager.exists(userId)) return true;
8928            PackageParser.Package p = filter.service.owner;
8929            if (p != null) {
8930                PackageSetting ps = (PackageSetting)p.mExtras;
8931                if (ps != null) {
8932                    // System apps are never considered stopped for purposes of
8933                    // filtering, because there may be no way for the user to
8934                    // actually re-launch them.
8935                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8936                            && ps.getStopped(userId);
8937                }
8938            }
8939            return false;
8940        }
8941
8942        @Override
8943        protected boolean isPackageForFilter(String packageName,
8944                PackageParser.ServiceIntentInfo info) {
8945            return packageName.equals(info.service.owner.packageName);
8946        }
8947
8948        @Override
8949        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8950                int match, int userId) {
8951            if (!sUserManager.exists(userId)) return null;
8952            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8953            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8954                return null;
8955            }
8956            final PackageParser.Service service = info.service;
8957            if (mSafeMode && (service.info.applicationInfo.flags
8958                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8959                return null;
8960            }
8961            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8962            if (ps == null) {
8963                return null;
8964            }
8965            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8966                    ps.readUserState(userId), userId);
8967            if (si == null) {
8968                return null;
8969            }
8970            final ResolveInfo res = new ResolveInfo();
8971            res.serviceInfo = si;
8972            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8973                res.filter = filter;
8974            }
8975            res.priority = info.getPriority();
8976            res.preferredOrder = service.owner.mPreferredOrder;
8977            res.match = match;
8978            res.isDefault = info.hasDefault;
8979            res.labelRes = info.labelRes;
8980            res.nonLocalizedLabel = info.nonLocalizedLabel;
8981            res.icon = info.icon;
8982            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8983            return res;
8984        }
8985
8986        @Override
8987        protected void sortResults(List<ResolveInfo> results) {
8988            Collections.sort(results, mResolvePrioritySorter);
8989        }
8990
8991        @Override
8992        protected void dumpFilter(PrintWriter out, String prefix,
8993                PackageParser.ServiceIntentInfo filter) {
8994            out.print(prefix); out.print(
8995                    Integer.toHexString(System.identityHashCode(filter.service)));
8996                    out.print(' ');
8997                    filter.service.printComponentShortName(out);
8998                    out.print(" filter ");
8999                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9000        }
9001
9002        @Override
9003        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9004            return filter.service;
9005        }
9006
9007        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9008            PackageParser.Service service = (PackageParser.Service)label;
9009            out.print(prefix); out.print(
9010                    Integer.toHexString(System.identityHashCode(service)));
9011                    out.print(' ');
9012                    service.printComponentShortName(out);
9013            if (count > 1) {
9014                out.print(" ("); out.print(count); out.print(" filters)");
9015            }
9016            out.println();
9017        }
9018
9019//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9020//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9021//            final List<ResolveInfo> retList = Lists.newArrayList();
9022//            while (i.hasNext()) {
9023//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9024//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9025//                    retList.add(resolveInfo);
9026//                }
9027//            }
9028//            return retList;
9029//        }
9030
9031        // Keys are String (activity class name), values are Activity.
9032        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9033                = new ArrayMap<ComponentName, PackageParser.Service>();
9034        private int mFlags;
9035    };
9036
9037    private final class ProviderIntentResolver
9038            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9040                boolean defaultOnly, int userId) {
9041            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9042            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9043        }
9044
9045        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9046                int userId) {
9047            if (!sUserManager.exists(userId))
9048                return null;
9049            mFlags = flags;
9050            return super.queryIntent(intent, resolvedType,
9051                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9052        }
9053
9054        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9055                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9056            if (!sUserManager.exists(userId))
9057                return null;
9058            if (packageProviders == null) {
9059                return null;
9060            }
9061            mFlags = flags;
9062            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9063            final int N = packageProviders.size();
9064            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9065                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9066
9067            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9068            for (int i = 0; i < N; ++i) {
9069                intentFilters = packageProviders.get(i).intents;
9070                if (intentFilters != null && intentFilters.size() > 0) {
9071                    PackageParser.ProviderIntentInfo[] array =
9072                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9073                    intentFilters.toArray(array);
9074                    listCut.add(array);
9075                }
9076            }
9077            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9078        }
9079
9080        public final void addProvider(PackageParser.Provider p) {
9081            if (mProviders.containsKey(p.getComponentName())) {
9082                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9083                return;
9084            }
9085
9086            mProviders.put(p.getComponentName(), p);
9087            if (DEBUG_SHOW_INFO) {
9088                Log.v(TAG, "  "
9089                        + (p.info.nonLocalizedLabel != null
9090                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9091                Log.v(TAG, "    Class=" + p.info.name);
9092            }
9093            final int NI = p.intents.size();
9094            int j;
9095            for (j = 0; j < NI; j++) {
9096                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9097                if (DEBUG_SHOW_INFO) {
9098                    Log.v(TAG, "    IntentFilter:");
9099                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9100                }
9101                if (!intent.debugCheck()) {
9102                    Log.w(TAG, "==> For Provider " + p.info.name);
9103                }
9104                addFilter(intent);
9105            }
9106        }
9107
9108        public final void removeProvider(PackageParser.Provider p) {
9109            mProviders.remove(p.getComponentName());
9110            if (DEBUG_SHOW_INFO) {
9111                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9112                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9113                Log.v(TAG, "    Class=" + p.info.name);
9114            }
9115            final int NI = p.intents.size();
9116            int j;
9117            for (j = 0; j < NI; j++) {
9118                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9119                if (DEBUG_SHOW_INFO) {
9120                    Log.v(TAG, "    IntentFilter:");
9121                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9122                }
9123                removeFilter(intent);
9124            }
9125        }
9126
9127        @Override
9128        protected boolean allowFilterResult(
9129                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9130            ProviderInfo filterPi = filter.provider.info;
9131            for (int i = dest.size() - 1; i >= 0; i--) {
9132                ProviderInfo destPi = dest.get(i).providerInfo;
9133                if (destPi.name == filterPi.name
9134                        && destPi.packageName == filterPi.packageName) {
9135                    return false;
9136                }
9137            }
9138            return true;
9139        }
9140
9141        @Override
9142        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9143            return new PackageParser.ProviderIntentInfo[size];
9144        }
9145
9146        @Override
9147        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9148            if (!sUserManager.exists(userId))
9149                return true;
9150            PackageParser.Package p = filter.provider.owner;
9151            if (p != null) {
9152                PackageSetting ps = (PackageSetting) p.mExtras;
9153                if (ps != null) {
9154                    // System apps are never considered stopped for purposes of
9155                    // filtering, because there may be no way for the user to
9156                    // actually re-launch them.
9157                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9158                            && ps.getStopped(userId);
9159                }
9160            }
9161            return false;
9162        }
9163
9164        @Override
9165        protected boolean isPackageForFilter(String packageName,
9166                PackageParser.ProviderIntentInfo info) {
9167            return packageName.equals(info.provider.owner.packageName);
9168        }
9169
9170        @Override
9171        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9172                int match, int userId) {
9173            if (!sUserManager.exists(userId))
9174                return null;
9175            final PackageParser.ProviderIntentInfo info = filter;
9176            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9177                return null;
9178            }
9179            final PackageParser.Provider provider = info.provider;
9180            if (mSafeMode && (provider.info.applicationInfo.flags
9181                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9182                return null;
9183            }
9184            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9185            if (ps == null) {
9186                return null;
9187            }
9188            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9189                    ps.readUserState(userId), userId);
9190            if (pi == null) {
9191                return null;
9192            }
9193            final ResolveInfo res = new ResolveInfo();
9194            res.providerInfo = pi;
9195            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9196                res.filter = filter;
9197            }
9198            res.priority = info.getPriority();
9199            res.preferredOrder = provider.owner.mPreferredOrder;
9200            res.match = match;
9201            res.isDefault = info.hasDefault;
9202            res.labelRes = info.labelRes;
9203            res.nonLocalizedLabel = info.nonLocalizedLabel;
9204            res.icon = info.icon;
9205            res.system = res.providerInfo.applicationInfo.isSystemApp();
9206            return res;
9207        }
9208
9209        @Override
9210        protected void sortResults(List<ResolveInfo> results) {
9211            Collections.sort(results, mResolvePrioritySorter);
9212        }
9213
9214        @Override
9215        protected void dumpFilter(PrintWriter out, String prefix,
9216                PackageParser.ProviderIntentInfo filter) {
9217            out.print(prefix);
9218            out.print(
9219                    Integer.toHexString(System.identityHashCode(filter.provider)));
9220            out.print(' ');
9221            filter.provider.printComponentShortName(out);
9222            out.print(" filter ");
9223            out.println(Integer.toHexString(System.identityHashCode(filter)));
9224        }
9225
9226        @Override
9227        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9228            return filter.provider;
9229        }
9230
9231        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9232            PackageParser.Provider provider = (PackageParser.Provider)label;
9233            out.print(prefix); out.print(
9234                    Integer.toHexString(System.identityHashCode(provider)));
9235                    out.print(' ');
9236                    provider.printComponentShortName(out);
9237            if (count > 1) {
9238                out.print(" ("); out.print(count); out.print(" filters)");
9239            }
9240            out.println();
9241        }
9242
9243        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9244                = new ArrayMap<ComponentName, PackageParser.Provider>();
9245        private int mFlags;
9246    };
9247
9248    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9249            new Comparator<ResolveInfo>() {
9250        public int compare(ResolveInfo r1, ResolveInfo r2) {
9251            int v1 = r1.priority;
9252            int v2 = r2.priority;
9253            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9254            if (v1 != v2) {
9255                return (v1 > v2) ? -1 : 1;
9256            }
9257            v1 = r1.preferredOrder;
9258            v2 = r2.preferredOrder;
9259            if (v1 != v2) {
9260                return (v1 > v2) ? -1 : 1;
9261            }
9262            if (r1.isDefault != r2.isDefault) {
9263                return r1.isDefault ? -1 : 1;
9264            }
9265            v1 = r1.match;
9266            v2 = r2.match;
9267            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9268            if (v1 != v2) {
9269                return (v1 > v2) ? -1 : 1;
9270            }
9271            if (r1.system != r2.system) {
9272                return r1.system ? -1 : 1;
9273            }
9274            return 0;
9275        }
9276    };
9277
9278    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9279            new Comparator<ProviderInfo>() {
9280        public int compare(ProviderInfo p1, ProviderInfo p2) {
9281            final int v1 = p1.initOrder;
9282            final int v2 = p2.initOrder;
9283            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9284        }
9285    };
9286
9287    final void sendPackageBroadcast(final String action, final String pkg,
9288            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9289            final int[] userIds) {
9290        mHandler.post(new Runnable() {
9291            @Override
9292            public void run() {
9293                try {
9294                    final IActivityManager am = ActivityManagerNative.getDefault();
9295                    if (am == null) return;
9296                    final int[] resolvedUserIds;
9297                    if (userIds == null) {
9298                        resolvedUserIds = am.getRunningUserIds();
9299                    } else {
9300                        resolvedUserIds = userIds;
9301                    }
9302                    for (int id : resolvedUserIds) {
9303                        final Intent intent = new Intent(action,
9304                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9305                        if (extras != null) {
9306                            intent.putExtras(extras);
9307                        }
9308                        if (targetPkg != null) {
9309                            intent.setPackage(targetPkg);
9310                        }
9311                        // Modify the UID when posting to other users
9312                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9313                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9314                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9315                            intent.putExtra(Intent.EXTRA_UID, uid);
9316                        }
9317                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9318                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9319                        if (DEBUG_BROADCASTS) {
9320                            RuntimeException here = new RuntimeException("here");
9321                            here.fillInStackTrace();
9322                            Slog.d(TAG, "Sending to user " + id + ": "
9323                                    + intent.toShortString(false, true, false, false)
9324                                    + " " + intent.getExtras(), here);
9325                        }
9326                        am.broadcastIntent(null, intent, null, finishedReceiver,
9327                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9328                                null, finishedReceiver != null, false, id);
9329                    }
9330                } catch (RemoteException ex) {
9331                }
9332            }
9333        });
9334    }
9335
9336    /**
9337     * Check if the external storage media is available. This is true if there
9338     * is a mounted external storage medium or if the external storage is
9339     * emulated.
9340     */
9341    private boolean isExternalMediaAvailable() {
9342        return mMediaMounted || Environment.isExternalStorageEmulated();
9343    }
9344
9345    @Override
9346    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9347        // writer
9348        synchronized (mPackages) {
9349            if (!isExternalMediaAvailable()) {
9350                // If the external storage is no longer mounted at this point,
9351                // the caller may not have been able to delete all of this
9352                // packages files and can not delete any more.  Bail.
9353                return null;
9354            }
9355            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9356            if (lastPackage != null) {
9357                pkgs.remove(lastPackage);
9358            }
9359            if (pkgs.size() > 0) {
9360                return pkgs.get(0);
9361            }
9362        }
9363        return null;
9364    }
9365
9366    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9367        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9368                userId, andCode ? 1 : 0, packageName);
9369        if (mSystemReady) {
9370            msg.sendToTarget();
9371        } else {
9372            if (mPostSystemReadyMessages == null) {
9373                mPostSystemReadyMessages = new ArrayList<>();
9374            }
9375            mPostSystemReadyMessages.add(msg);
9376        }
9377    }
9378
9379    void startCleaningPackages() {
9380        // reader
9381        synchronized (mPackages) {
9382            if (!isExternalMediaAvailable()) {
9383                return;
9384            }
9385            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9386                return;
9387            }
9388        }
9389        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9390        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9391        IActivityManager am = ActivityManagerNative.getDefault();
9392        if (am != null) {
9393            try {
9394                am.startService(null, intent, null, mContext.getOpPackageName(),
9395                        UserHandle.USER_OWNER);
9396            } catch (RemoteException e) {
9397            }
9398        }
9399    }
9400
9401    @Override
9402    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9403            int installFlags, String installerPackageName, VerificationParams verificationParams,
9404            String packageAbiOverride) {
9405        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9406                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9407    }
9408
9409    @Override
9410    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9411            int installFlags, String installerPackageName, VerificationParams verificationParams,
9412            String packageAbiOverride, int userId) {
9413        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9414
9415        final int callingUid = Binder.getCallingUid();
9416        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9417
9418        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9419            try {
9420                if (observer != null) {
9421                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9422                }
9423            } catch (RemoteException re) {
9424            }
9425            return;
9426        }
9427
9428        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9429            installFlags |= PackageManager.INSTALL_FROM_ADB;
9430
9431        } else {
9432            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9433            // about installerPackageName.
9434
9435            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9436            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9437        }
9438
9439        UserHandle user;
9440        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9441            user = UserHandle.ALL;
9442        } else {
9443            user = new UserHandle(userId);
9444        }
9445
9446        // Only system components can circumvent runtime permissions when installing.
9447        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9448                && mContext.checkCallingOrSelfPermission(Manifest.permission
9449                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9450            throw new SecurityException("You need the "
9451                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9452                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9453        }
9454
9455        verificationParams.setInstallerUid(callingUid);
9456
9457        final File originFile = new File(originPath);
9458        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9459
9460        final Message msg = mHandler.obtainMessage(INIT_COPY);
9461        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9462                null, verificationParams, user, packageAbiOverride, null);
9463        mHandler.sendMessage(msg);
9464    }
9465
9466    void installStage(String packageName, File stagedDir, String stagedCid,
9467            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9468            String installerPackageName, int installerUid, UserHandle user) {
9469        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9470                params.referrerUri, installerUid, null);
9471        verifParams.setInstallerUid(installerUid);
9472
9473        final OriginInfo origin;
9474        if (stagedDir != null) {
9475            origin = OriginInfo.fromStagedFile(stagedDir);
9476        } else {
9477            origin = OriginInfo.fromStagedContainer(stagedCid);
9478        }
9479
9480        final Message msg = mHandler.obtainMessage(INIT_COPY);
9481        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9482                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9483                params.grantedRuntimePermissions);
9484        mHandler.sendMessage(msg);
9485    }
9486
9487    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9488        Bundle extras = new Bundle(1);
9489        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9490
9491        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9492                packageName, extras, null, null, new int[] {userId});
9493        try {
9494            IActivityManager am = ActivityManagerNative.getDefault();
9495            final boolean isSystem =
9496                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9497            if (isSystem && am.isUserRunning(userId, false)) {
9498                // The just-installed/enabled app is bundled on the system, so presumed
9499                // to be able to run automatically without needing an explicit launch.
9500                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9501                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9502                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9503                        .setPackage(packageName);
9504                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9505                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9506            }
9507        } catch (RemoteException e) {
9508            // shouldn't happen
9509            Slog.w(TAG, "Unable to bootstrap installed package", e);
9510        }
9511    }
9512
9513    @Override
9514    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9515            int userId) {
9516        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9517        PackageSetting pkgSetting;
9518        final int uid = Binder.getCallingUid();
9519        enforceCrossUserPermission(uid, userId, true, true,
9520                "setApplicationHiddenSetting for user " + userId);
9521
9522        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9523            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9524            return false;
9525        }
9526
9527        long callingId = Binder.clearCallingIdentity();
9528        try {
9529            boolean sendAdded = false;
9530            boolean sendRemoved = false;
9531            // writer
9532            synchronized (mPackages) {
9533                pkgSetting = mSettings.mPackages.get(packageName);
9534                if (pkgSetting == null) {
9535                    return false;
9536                }
9537                if (pkgSetting.getHidden(userId) != hidden) {
9538                    pkgSetting.setHidden(hidden, userId);
9539                    mSettings.writePackageRestrictionsLPr(userId);
9540                    if (hidden) {
9541                        sendRemoved = true;
9542                    } else {
9543                        sendAdded = true;
9544                    }
9545                }
9546            }
9547            if (sendAdded) {
9548                sendPackageAddedForUser(packageName, pkgSetting, userId);
9549                return true;
9550            }
9551            if (sendRemoved) {
9552                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9553                        "hiding pkg");
9554                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9555            }
9556        } finally {
9557            Binder.restoreCallingIdentity(callingId);
9558        }
9559        return false;
9560    }
9561
9562    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9563            int userId) {
9564        final PackageRemovedInfo info = new PackageRemovedInfo();
9565        info.removedPackage = packageName;
9566        info.removedUsers = new int[] {userId};
9567        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9568        info.sendBroadcast(false, false, false);
9569    }
9570
9571    /**
9572     * Returns true if application is not found or there was an error. Otherwise it returns
9573     * the hidden state of the package for the given user.
9574     */
9575    @Override
9576    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9577        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9578        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9579                false, "getApplicationHidden for user " + userId);
9580        PackageSetting pkgSetting;
9581        long callingId = Binder.clearCallingIdentity();
9582        try {
9583            // writer
9584            synchronized (mPackages) {
9585                pkgSetting = mSettings.mPackages.get(packageName);
9586                if (pkgSetting == null) {
9587                    return true;
9588                }
9589                return pkgSetting.getHidden(userId);
9590            }
9591        } finally {
9592            Binder.restoreCallingIdentity(callingId);
9593        }
9594    }
9595
9596    /**
9597     * @hide
9598     */
9599    @Override
9600    public int installExistingPackageAsUser(String packageName, int userId) {
9601        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9602                null);
9603        PackageSetting pkgSetting;
9604        final int uid = Binder.getCallingUid();
9605        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9606                + userId);
9607        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9608            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9609        }
9610
9611        long callingId = Binder.clearCallingIdentity();
9612        try {
9613            boolean sendAdded = false;
9614
9615            // writer
9616            synchronized (mPackages) {
9617                pkgSetting = mSettings.mPackages.get(packageName);
9618                if (pkgSetting == null) {
9619                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9620                }
9621                if (!pkgSetting.getInstalled(userId)) {
9622                    pkgSetting.setInstalled(true, userId);
9623                    pkgSetting.setHidden(false, userId);
9624                    mSettings.writePackageRestrictionsLPr(userId);
9625                    sendAdded = true;
9626                }
9627            }
9628
9629            if (sendAdded) {
9630                sendPackageAddedForUser(packageName, pkgSetting, userId);
9631            }
9632        } finally {
9633            Binder.restoreCallingIdentity(callingId);
9634        }
9635
9636        return PackageManager.INSTALL_SUCCEEDED;
9637    }
9638
9639    boolean isUserRestricted(int userId, String restrictionKey) {
9640        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9641        if (restrictions.getBoolean(restrictionKey, false)) {
9642            Log.w(TAG, "User is restricted: " + restrictionKey);
9643            return true;
9644        }
9645        return false;
9646    }
9647
9648    @Override
9649    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9650        mContext.enforceCallingOrSelfPermission(
9651                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9652                "Only package verification agents can verify applications");
9653
9654        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9655        final PackageVerificationResponse response = new PackageVerificationResponse(
9656                verificationCode, Binder.getCallingUid());
9657        msg.arg1 = id;
9658        msg.obj = response;
9659        mHandler.sendMessage(msg);
9660    }
9661
9662    @Override
9663    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9664            long millisecondsToDelay) {
9665        mContext.enforceCallingOrSelfPermission(
9666                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9667                "Only package verification agents can extend verification timeouts");
9668
9669        final PackageVerificationState state = mPendingVerification.get(id);
9670        final PackageVerificationResponse response = new PackageVerificationResponse(
9671                verificationCodeAtTimeout, Binder.getCallingUid());
9672
9673        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9674            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9675        }
9676        if (millisecondsToDelay < 0) {
9677            millisecondsToDelay = 0;
9678        }
9679        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9680                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9681            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9682        }
9683
9684        if ((state != null) && !state.timeoutExtended()) {
9685            state.extendTimeout();
9686
9687            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9688            msg.arg1 = id;
9689            msg.obj = response;
9690            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9691        }
9692    }
9693
9694    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9695            int verificationCode, UserHandle user) {
9696        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9697        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9698        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9699        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9700        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9701
9702        mContext.sendBroadcastAsUser(intent, user,
9703                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9704    }
9705
9706    private ComponentName matchComponentForVerifier(String packageName,
9707            List<ResolveInfo> receivers) {
9708        ActivityInfo targetReceiver = null;
9709
9710        final int NR = receivers.size();
9711        for (int i = 0; i < NR; i++) {
9712            final ResolveInfo info = receivers.get(i);
9713            if (info.activityInfo == null) {
9714                continue;
9715            }
9716
9717            if (packageName.equals(info.activityInfo.packageName)) {
9718                targetReceiver = info.activityInfo;
9719                break;
9720            }
9721        }
9722
9723        if (targetReceiver == null) {
9724            return null;
9725        }
9726
9727        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9728    }
9729
9730    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9731            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9732        if (pkgInfo.verifiers.length == 0) {
9733            return null;
9734        }
9735
9736        final int N = pkgInfo.verifiers.length;
9737        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9738        for (int i = 0; i < N; i++) {
9739            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9740
9741            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9742                    receivers);
9743            if (comp == null) {
9744                continue;
9745            }
9746
9747            final int verifierUid = getUidForVerifier(verifierInfo);
9748            if (verifierUid == -1) {
9749                continue;
9750            }
9751
9752            if (DEBUG_VERIFY) {
9753                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9754                        + " with the correct signature");
9755            }
9756            sufficientVerifiers.add(comp);
9757            verificationState.addSufficientVerifier(verifierUid);
9758        }
9759
9760        return sufficientVerifiers;
9761    }
9762
9763    private int getUidForVerifier(VerifierInfo verifierInfo) {
9764        synchronized (mPackages) {
9765            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9766            if (pkg == null) {
9767                return -1;
9768            } else if (pkg.mSignatures.length != 1) {
9769                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9770                        + " has more than one signature; ignoring");
9771                return -1;
9772            }
9773
9774            /*
9775             * If the public key of the package's signature does not match
9776             * our expected public key, then this is a different package and
9777             * we should skip.
9778             */
9779
9780            final byte[] expectedPublicKey;
9781            try {
9782                final Signature verifierSig = pkg.mSignatures[0];
9783                final PublicKey publicKey = verifierSig.getPublicKey();
9784                expectedPublicKey = publicKey.getEncoded();
9785            } catch (CertificateException e) {
9786                return -1;
9787            }
9788
9789            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9790
9791            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9792                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9793                        + " does not have the expected public key; ignoring");
9794                return -1;
9795            }
9796
9797            return pkg.applicationInfo.uid;
9798        }
9799    }
9800
9801    @Override
9802    public void finishPackageInstall(int token) {
9803        enforceSystemOrRoot("Only the system is allowed to finish installs");
9804
9805        if (DEBUG_INSTALL) {
9806            Slog.v(TAG, "BM finishing package install for " + token);
9807        }
9808
9809        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9810        mHandler.sendMessage(msg);
9811    }
9812
9813    /**
9814     * Get the verification agent timeout.
9815     *
9816     * @return verification timeout in milliseconds
9817     */
9818    private long getVerificationTimeout() {
9819        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9820                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9821                DEFAULT_VERIFICATION_TIMEOUT);
9822    }
9823
9824    /**
9825     * Get the default verification agent response code.
9826     *
9827     * @return default verification response code
9828     */
9829    private int getDefaultVerificationResponse() {
9830        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9831                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9832                DEFAULT_VERIFICATION_RESPONSE);
9833    }
9834
9835    /**
9836     * Check whether or not package verification has been enabled.
9837     *
9838     * @return true if verification should be performed
9839     */
9840    private boolean isVerificationEnabled(int userId, int installFlags) {
9841        if (!DEFAULT_VERIFY_ENABLE) {
9842            return false;
9843        }
9844
9845        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9846
9847        // Check if installing from ADB
9848        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9849            // Do not run verification in a test harness environment
9850            if (ActivityManager.isRunningInTestHarness()) {
9851                return false;
9852            }
9853            if (ensureVerifyAppsEnabled) {
9854                return true;
9855            }
9856            // Check if the developer does not want package verification for ADB installs
9857            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9858                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9859                return false;
9860            }
9861        }
9862
9863        if (ensureVerifyAppsEnabled) {
9864            return true;
9865        }
9866
9867        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9868                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9869    }
9870
9871    @Override
9872    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9873            throws RemoteException {
9874        mContext.enforceCallingOrSelfPermission(
9875                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9876                "Only intentfilter verification agents can verify applications");
9877
9878        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9879        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9880                Binder.getCallingUid(), verificationCode, failedDomains);
9881        msg.arg1 = id;
9882        msg.obj = response;
9883        mHandler.sendMessage(msg);
9884    }
9885
9886    @Override
9887    public int getIntentVerificationStatus(String packageName, int userId) {
9888        synchronized (mPackages) {
9889            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9890        }
9891    }
9892
9893    @Override
9894    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9895        mContext.enforceCallingOrSelfPermission(
9896                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9897
9898        boolean result = false;
9899        synchronized (mPackages) {
9900            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9901        }
9902        if (result) {
9903            scheduleWritePackageRestrictionsLocked(userId);
9904        }
9905        return result;
9906    }
9907
9908    @Override
9909    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9910        synchronized (mPackages) {
9911            return mSettings.getIntentFilterVerificationsLPr(packageName);
9912        }
9913    }
9914
9915    @Override
9916    public List<IntentFilter> getAllIntentFilters(String packageName) {
9917        if (TextUtils.isEmpty(packageName)) {
9918            return Collections.<IntentFilter>emptyList();
9919        }
9920        synchronized (mPackages) {
9921            PackageParser.Package pkg = mPackages.get(packageName);
9922            if (pkg == null || pkg.activities == null) {
9923                return Collections.<IntentFilter>emptyList();
9924            }
9925            final int count = pkg.activities.size();
9926            ArrayList<IntentFilter> result = new ArrayList<>();
9927            for (int n=0; n<count; n++) {
9928                PackageParser.Activity activity = pkg.activities.get(n);
9929                if (activity.intents != null || activity.intents.size() > 0) {
9930                    result.addAll(activity.intents);
9931                }
9932            }
9933            return result;
9934        }
9935    }
9936
9937    @Override
9938    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9939        mContext.enforceCallingOrSelfPermission(
9940                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9941
9942        synchronized (mPackages) {
9943            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9944            if (packageName != null) {
9945                result |= updateIntentVerificationStatus(packageName,
9946                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9947                        UserHandle.myUserId());
9948                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9949                        packageName, userId);
9950            }
9951            return result;
9952        }
9953    }
9954
9955    @Override
9956    public String getDefaultBrowserPackageName(int userId) {
9957        synchronized (mPackages) {
9958            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9959        }
9960    }
9961
9962    /**
9963     * Get the "allow unknown sources" setting.
9964     *
9965     * @return the current "allow unknown sources" setting
9966     */
9967    private int getUnknownSourcesSettings() {
9968        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9969                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9970                -1);
9971    }
9972
9973    @Override
9974    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9975        final int uid = Binder.getCallingUid();
9976        // writer
9977        synchronized (mPackages) {
9978            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9979            if (targetPackageSetting == null) {
9980                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9981            }
9982
9983            PackageSetting installerPackageSetting;
9984            if (installerPackageName != null) {
9985                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9986                if (installerPackageSetting == null) {
9987                    throw new IllegalArgumentException("Unknown installer package: "
9988                            + installerPackageName);
9989                }
9990            } else {
9991                installerPackageSetting = null;
9992            }
9993
9994            Signature[] callerSignature;
9995            Object obj = mSettings.getUserIdLPr(uid);
9996            if (obj != null) {
9997                if (obj instanceof SharedUserSetting) {
9998                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9999                } else if (obj instanceof PackageSetting) {
10000                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10001                } else {
10002                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10003                }
10004            } else {
10005                throw new SecurityException("Unknown calling uid " + uid);
10006            }
10007
10008            // Verify: can't set installerPackageName to a package that is
10009            // not signed with the same cert as the caller.
10010            if (installerPackageSetting != null) {
10011                if (compareSignatures(callerSignature,
10012                        installerPackageSetting.signatures.mSignatures)
10013                        != PackageManager.SIGNATURE_MATCH) {
10014                    throw new SecurityException(
10015                            "Caller does not have same cert as new installer package "
10016                            + installerPackageName);
10017                }
10018            }
10019
10020            // Verify: if target already has an installer package, it must
10021            // be signed with the same cert as the caller.
10022            if (targetPackageSetting.installerPackageName != null) {
10023                PackageSetting setting = mSettings.mPackages.get(
10024                        targetPackageSetting.installerPackageName);
10025                // If the currently set package isn't valid, then it's always
10026                // okay to change it.
10027                if (setting != null) {
10028                    if (compareSignatures(callerSignature,
10029                            setting.signatures.mSignatures)
10030                            != PackageManager.SIGNATURE_MATCH) {
10031                        throw new SecurityException(
10032                                "Caller does not have same cert as old installer package "
10033                                + targetPackageSetting.installerPackageName);
10034                    }
10035                }
10036            }
10037
10038            // Okay!
10039            targetPackageSetting.installerPackageName = installerPackageName;
10040            scheduleWriteSettingsLocked();
10041        }
10042    }
10043
10044    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10045        // Queue up an async operation since the package installation may take a little while.
10046        mHandler.post(new Runnable() {
10047            public void run() {
10048                mHandler.removeCallbacks(this);
10049                 // Result object to be returned
10050                PackageInstalledInfo res = new PackageInstalledInfo();
10051                res.returnCode = currentStatus;
10052                res.uid = -1;
10053                res.pkg = null;
10054                res.removedInfo = new PackageRemovedInfo();
10055                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10056                    args.doPreInstall(res.returnCode);
10057                    synchronized (mInstallLock) {
10058                        installPackageLI(args, res);
10059                    }
10060                    args.doPostInstall(res.returnCode, res.uid);
10061                }
10062
10063                // A restore should be performed at this point if (a) the install
10064                // succeeded, (b) the operation is not an update, and (c) the new
10065                // package has not opted out of backup participation.
10066                final boolean update = res.removedInfo.removedPackage != null;
10067                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10068                boolean doRestore = !update
10069                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10070
10071                // Set up the post-install work request bookkeeping.  This will be used
10072                // and cleaned up by the post-install event handling regardless of whether
10073                // there's a restore pass performed.  Token values are >= 1.
10074                int token;
10075                if (mNextInstallToken < 0) mNextInstallToken = 1;
10076                token = mNextInstallToken++;
10077
10078                PostInstallData data = new PostInstallData(args, res);
10079                mRunningInstalls.put(token, data);
10080                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10081
10082                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10083                    // Pass responsibility to the Backup Manager.  It will perform a
10084                    // restore if appropriate, then pass responsibility back to the
10085                    // Package Manager to run the post-install observer callbacks
10086                    // and broadcasts.
10087                    IBackupManager bm = IBackupManager.Stub.asInterface(
10088                            ServiceManager.getService(Context.BACKUP_SERVICE));
10089                    if (bm != null) {
10090                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10091                                + " to BM for possible restore");
10092                        try {
10093                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10094                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10095                            } else {
10096                                doRestore = false;
10097                            }
10098                        } catch (RemoteException e) {
10099                            // can't happen; the backup manager is local
10100                        } catch (Exception e) {
10101                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10102                            doRestore = false;
10103                        }
10104                    } else {
10105                        Slog.e(TAG, "Backup Manager not found!");
10106                        doRestore = false;
10107                    }
10108                }
10109
10110                if (!doRestore) {
10111                    // No restore possible, or the Backup Manager was mysteriously not
10112                    // available -- just fire the post-install work request directly.
10113                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10114                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10115                    mHandler.sendMessage(msg);
10116                }
10117            }
10118        });
10119    }
10120
10121    private abstract class HandlerParams {
10122        private static final int MAX_RETRIES = 4;
10123
10124        /**
10125         * Number of times startCopy() has been attempted and had a non-fatal
10126         * error.
10127         */
10128        private int mRetries = 0;
10129
10130        /** User handle for the user requesting the information or installation. */
10131        private final UserHandle mUser;
10132
10133        HandlerParams(UserHandle user) {
10134            mUser = user;
10135        }
10136
10137        UserHandle getUser() {
10138            return mUser;
10139        }
10140
10141        final boolean startCopy() {
10142            boolean res;
10143            try {
10144                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10145
10146                if (++mRetries > MAX_RETRIES) {
10147                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10148                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10149                    handleServiceError();
10150                    return false;
10151                } else {
10152                    handleStartCopy();
10153                    res = true;
10154                }
10155            } catch (RemoteException e) {
10156                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10157                mHandler.sendEmptyMessage(MCS_RECONNECT);
10158                res = false;
10159            }
10160            handleReturnCode();
10161            return res;
10162        }
10163
10164        final void serviceError() {
10165            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10166            handleServiceError();
10167            handleReturnCode();
10168        }
10169
10170        abstract void handleStartCopy() throws RemoteException;
10171        abstract void handleServiceError();
10172        abstract void handleReturnCode();
10173    }
10174
10175    class MeasureParams extends HandlerParams {
10176        private final PackageStats mStats;
10177        private boolean mSuccess;
10178
10179        private final IPackageStatsObserver mObserver;
10180
10181        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10182            super(new UserHandle(stats.userHandle));
10183            mObserver = observer;
10184            mStats = stats;
10185        }
10186
10187        @Override
10188        public String toString() {
10189            return "MeasureParams{"
10190                + Integer.toHexString(System.identityHashCode(this))
10191                + " " + mStats.packageName + "}";
10192        }
10193
10194        @Override
10195        void handleStartCopy() throws RemoteException {
10196            synchronized (mInstallLock) {
10197                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10198            }
10199
10200            if (mSuccess) {
10201                final boolean mounted;
10202                if (Environment.isExternalStorageEmulated()) {
10203                    mounted = true;
10204                } else {
10205                    final String status = Environment.getExternalStorageState();
10206                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10207                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10208                }
10209
10210                if (mounted) {
10211                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10212
10213                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10214                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10215
10216                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10217                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10218
10219                    // Always subtract cache size, since it's a subdirectory
10220                    mStats.externalDataSize -= mStats.externalCacheSize;
10221
10222                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10223                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10224
10225                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10226                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10227                }
10228            }
10229        }
10230
10231        @Override
10232        void handleReturnCode() {
10233            if (mObserver != null) {
10234                try {
10235                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10236                } catch (RemoteException e) {
10237                    Slog.i(TAG, "Observer no longer exists.");
10238                }
10239            }
10240        }
10241
10242        @Override
10243        void handleServiceError() {
10244            Slog.e(TAG, "Could not measure application " + mStats.packageName
10245                            + " external storage");
10246        }
10247    }
10248
10249    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10250            throws RemoteException {
10251        long result = 0;
10252        for (File path : paths) {
10253            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10254        }
10255        return result;
10256    }
10257
10258    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10259        for (File path : paths) {
10260            try {
10261                mcs.clearDirectory(path.getAbsolutePath());
10262            } catch (RemoteException e) {
10263            }
10264        }
10265    }
10266
10267    static class OriginInfo {
10268        /**
10269         * Location where install is coming from, before it has been
10270         * copied/renamed into place. This could be a single monolithic APK
10271         * file, or a cluster directory. This location may be untrusted.
10272         */
10273        final File file;
10274        final String cid;
10275
10276        /**
10277         * Flag indicating that {@link #file} or {@link #cid} has already been
10278         * staged, meaning downstream users don't need to defensively copy the
10279         * contents.
10280         */
10281        final boolean staged;
10282
10283        /**
10284         * Flag indicating that {@link #file} or {@link #cid} is an already
10285         * installed app that is being moved.
10286         */
10287        final boolean existing;
10288
10289        final String resolvedPath;
10290        final File resolvedFile;
10291
10292        static OriginInfo fromNothing() {
10293            return new OriginInfo(null, null, false, false);
10294        }
10295
10296        static OriginInfo fromUntrustedFile(File file) {
10297            return new OriginInfo(file, null, false, false);
10298        }
10299
10300        static OriginInfo fromExistingFile(File file) {
10301            return new OriginInfo(file, null, false, true);
10302        }
10303
10304        static OriginInfo fromStagedFile(File file) {
10305            return new OriginInfo(file, null, true, false);
10306        }
10307
10308        static OriginInfo fromStagedContainer(String cid) {
10309            return new OriginInfo(null, cid, true, false);
10310        }
10311
10312        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10313            this.file = file;
10314            this.cid = cid;
10315            this.staged = staged;
10316            this.existing = existing;
10317
10318            if (cid != null) {
10319                resolvedPath = PackageHelper.getSdDir(cid);
10320                resolvedFile = new File(resolvedPath);
10321            } else if (file != null) {
10322                resolvedPath = file.getAbsolutePath();
10323                resolvedFile = file;
10324            } else {
10325                resolvedPath = null;
10326                resolvedFile = null;
10327            }
10328        }
10329    }
10330
10331    class MoveInfo {
10332        final int moveId;
10333        final String fromUuid;
10334        final String toUuid;
10335        final String packageName;
10336        final String dataAppName;
10337        final int appId;
10338        final String seinfo;
10339
10340        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10341                String dataAppName, int appId, String seinfo) {
10342            this.moveId = moveId;
10343            this.fromUuid = fromUuid;
10344            this.toUuid = toUuid;
10345            this.packageName = packageName;
10346            this.dataAppName = dataAppName;
10347            this.appId = appId;
10348            this.seinfo = seinfo;
10349        }
10350    }
10351
10352    class InstallParams extends HandlerParams {
10353        final OriginInfo origin;
10354        final MoveInfo move;
10355        final IPackageInstallObserver2 observer;
10356        int installFlags;
10357        final String installerPackageName;
10358        final String volumeUuid;
10359        final VerificationParams verificationParams;
10360        private InstallArgs mArgs;
10361        private int mRet;
10362        final String packageAbiOverride;
10363        final String[] grantedRuntimePermissions;
10364
10365
10366        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10367                int installFlags, String installerPackageName, String volumeUuid,
10368                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10369                String[] grantedPermissions) {
10370            super(user);
10371            this.origin = origin;
10372            this.move = move;
10373            this.observer = observer;
10374            this.installFlags = installFlags;
10375            this.installerPackageName = installerPackageName;
10376            this.volumeUuid = volumeUuid;
10377            this.verificationParams = verificationParams;
10378            this.packageAbiOverride = packageAbiOverride;
10379            this.grantedRuntimePermissions = grantedPermissions;
10380        }
10381
10382        @Override
10383        public String toString() {
10384            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10385                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10386        }
10387
10388        public ManifestDigest getManifestDigest() {
10389            if (verificationParams == null) {
10390                return null;
10391            }
10392            return verificationParams.getManifestDigest();
10393        }
10394
10395        private int installLocationPolicy(PackageInfoLite pkgLite) {
10396            String packageName = pkgLite.packageName;
10397            int installLocation = pkgLite.installLocation;
10398            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10399            // reader
10400            synchronized (mPackages) {
10401                PackageParser.Package pkg = mPackages.get(packageName);
10402                if (pkg != null) {
10403                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10404                        // Check for downgrading.
10405                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10406                            try {
10407                                checkDowngrade(pkg, pkgLite);
10408                            } catch (PackageManagerException e) {
10409                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10410                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10411                            }
10412                        }
10413                        // Check for updated system application.
10414                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10415                            if (onSd) {
10416                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10417                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10418                            }
10419                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10420                        } else {
10421                            if (onSd) {
10422                                // Install flag overrides everything.
10423                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10424                            }
10425                            // If current upgrade specifies particular preference
10426                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10427                                // Application explicitly specified internal.
10428                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10429                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10430                                // App explictly prefers external. Let policy decide
10431                            } else {
10432                                // Prefer previous location
10433                                if (isExternal(pkg)) {
10434                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10435                                }
10436                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10437                            }
10438                        }
10439                    } else {
10440                        // Invalid install. Return error code
10441                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10442                    }
10443                }
10444            }
10445            // All the special cases have been taken care of.
10446            // Return result based on recommended install location.
10447            if (onSd) {
10448                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10449            }
10450            return pkgLite.recommendedInstallLocation;
10451        }
10452
10453        /*
10454         * Invoke remote method to get package information and install
10455         * location values. Override install location based on default
10456         * policy if needed and then create install arguments based
10457         * on the install location.
10458         */
10459        public void handleStartCopy() throws RemoteException {
10460            int ret = PackageManager.INSTALL_SUCCEEDED;
10461
10462            // If we're already staged, we've firmly committed to an install location
10463            if (origin.staged) {
10464                if (origin.file != null) {
10465                    installFlags |= PackageManager.INSTALL_INTERNAL;
10466                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10467                } else if (origin.cid != null) {
10468                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10469                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10470                } else {
10471                    throw new IllegalStateException("Invalid stage location");
10472                }
10473            }
10474
10475            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10476            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10477
10478            PackageInfoLite pkgLite = null;
10479
10480            if (onInt && onSd) {
10481                // Check if both bits are set.
10482                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10483                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10484            } else {
10485                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10486                        packageAbiOverride);
10487
10488                /*
10489                 * If we have too little free space, try to free cache
10490                 * before giving up.
10491                 */
10492                if (!origin.staged && pkgLite.recommendedInstallLocation
10493                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10494                    // TODO: focus freeing disk space on the target device
10495                    final StorageManager storage = StorageManager.from(mContext);
10496                    final long lowThreshold = storage.getStorageLowBytes(
10497                            Environment.getDataDirectory());
10498
10499                    final long sizeBytes = mContainerService.calculateInstalledSize(
10500                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10501
10502                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10503                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10504                                installFlags, packageAbiOverride);
10505                    }
10506
10507                    /*
10508                     * The cache free must have deleted the file we
10509                     * downloaded to install.
10510                     *
10511                     * TODO: fix the "freeCache" call to not delete
10512                     *       the file we care about.
10513                     */
10514                    if (pkgLite.recommendedInstallLocation
10515                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10516                        pkgLite.recommendedInstallLocation
10517                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10518                    }
10519                }
10520            }
10521
10522            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10523                int loc = pkgLite.recommendedInstallLocation;
10524                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10525                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10526                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10527                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10528                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10529                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10530                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10531                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10532                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10533                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10534                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10535                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10536                } else {
10537                    // Override with defaults if needed.
10538                    loc = installLocationPolicy(pkgLite);
10539                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10540                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10541                    } else if (!onSd && !onInt) {
10542                        // Override install location with flags
10543                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10544                            // Set the flag to install on external media.
10545                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10546                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10547                        } else {
10548                            // Make sure the flag for installing on external
10549                            // media is unset
10550                            installFlags |= PackageManager.INSTALL_INTERNAL;
10551                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10552                        }
10553                    }
10554                }
10555            }
10556
10557            final InstallArgs args = createInstallArgs(this);
10558            mArgs = args;
10559
10560            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10561                 /*
10562                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10563                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10564                 */
10565                int userIdentifier = getUser().getIdentifier();
10566                if (userIdentifier == UserHandle.USER_ALL
10567                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10568                    userIdentifier = UserHandle.USER_OWNER;
10569                }
10570
10571                /*
10572                 * Determine if we have any installed package verifiers. If we
10573                 * do, then we'll defer to them to verify the packages.
10574                 */
10575                final int requiredUid = mRequiredVerifierPackage == null ? -1
10576                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10577                if (!origin.existing && requiredUid != -1
10578                        && isVerificationEnabled(userIdentifier, installFlags)) {
10579                    final Intent verification = new Intent(
10580                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10581                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10582                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10583                            PACKAGE_MIME_TYPE);
10584                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10585
10586                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10587                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10588                            0 /* TODO: Which userId? */);
10589
10590                    if (DEBUG_VERIFY) {
10591                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10592                                + verification.toString() + " with " + pkgLite.verifiers.length
10593                                + " optional verifiers");
10594                    }
10595
10596                    final int verificationId = mPendingVerificationToken++;
10597
10598                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10599
10600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10601                            installerPackageName);
10602
10603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10604                            installFlags);
10605
10606                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10607                            pkgLite.packageName);
10608
10609                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10610                            pkgLite.versionCode);
10611
10612                    if (verificationParams != null) {
10613                        if (verificationParams.getVerificationURI() != null) {
10614                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10615                                 verificationParams.getVerificationURI());
10616                        }
10617                        if (verificationParams.getOriginatingURI() != null) {
10618                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10619                                  verificationParams.getOriginatingURI());
10620                        }
10621                        if (verificationParams.getReferrer() != null) {
10622                            verification.putExtra(Intent.EXTRA_REFERRER,
10623                                  verificationParams.getReferrer());
10624                        }
10625                        if (verificationParams.getOriginatingUid() >= 0) {
10626                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10627                                  verificationParams.getOriginatingUid());
10628                        }
10629                        if (verificationParams.getInstallerUid() >= 0) {
10630                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10631                                  verificationParams.getInstallerUid());
10632                        }
10633                    }
10634
10635                    final PackageVerificationState verificationState = new PackageVerificationState(
10636                            requiredUid, args);
10637
10638                    mPendingVerification.append(verificationId, verificationState);
10639
10640                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10641                            receivers, verificationState);
10642
10643                    /*
10644                     * If any sufficient verifiers were listed in the package
10645                     * manifest, attempt to ask them.
10646                     */
10647                    if (sufficientVerifiers != null) {
10648                        final int N = sufficientVerifiers.size();
10649                        if (N == 0) {
10650                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10651                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10652                        } else {
10653                            for (int i = 0; i < N; i++) {
10654                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10655
10656                                final Intent sufficientIntent = new Intent(verification);
10657                                sufficientIntent.setComponent(verifierComponent);
10658
10659                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10660                            }
10661                        }
10662                    }
10663
10664                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10665                            mRequiredVerifierPackage, receivers);
10666                    if (ret == PackageManager.INSTALL_SUCCEEDED
10667                            && mRequiredVerifierPackage != null) {
10668                        /*
10669                         * Send the intent to the required verification agent,
10670                         * but only start the verification timeout after the
10671                         * target BroadcastReceivers have run.
10672                         */
10673                        verification.setComponent(requiredVerifierComponent);
10674                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10675                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10676                                new BroadcastReceiver() {
10677                                    @Override
10678                                    public void onReceive(Context context, Intent intent) {
10679                                        final Message msg = mHandler
10680                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10681                                        msg.arg1 = verificationId;
10682                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10683                                    }
10684                                }, null, 0, null, null);
10685
10686                        /*
10687                         * We don't want the copy to proceed until verification
10688                         * succeeds, so null out this field.
10689                         */
10690                        mArgs = null;
10691                    }
10692                } else {
10693                    /*
10694                     * No package verification is enabled, so immediately start
10695                     * the remote call to initiate copy using temporary file.
10696                     */
10697                    ret = args.copyApk(mContainerService, true);
10698                }
10699            }
10700
10701            mRet = ret;
10702        }
10703
10704        @Override
10705        void handleReturnCode() {
10706            // If mArgs is null, then MCS couldn't be reached. When it
10707            // reconnects, it will try again to install. At that point, this
10708            // will succeed.
10709            if (mArgs != null) {
10710                processPendingInstall(mArgs, mRet);
10711            }
10712        }
10713
10714        @Override
10715        void handleServiceError() {
10716            mArgs = createInstallArgs(this);
10717            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10718        }
10719
10720        public boolean isForwardLocked() {
10721            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10722        }
10723    }
10724
10725    /**
10726     * Used during creation of InstallArgs
10727     *
10728     * @param installFlags package installation flags
10729     * @return true if should be installed on external storage
10730     */
10731    private static boolean installOnExternalAsec(int installFlags) {
10732        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10733            return false;
10734        }
10735        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10736            return true;
10737        }
10738        return false;
10739    }
10740
10741    /**
10742     * Used during creation of InstallArgs
10743     *
10744     * @param installFlags package installation flags
10745     * @return true if should be installed as forward locked
10746     */
10747    private static boolean installForwardLocked(int installFlags) {
10748        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10749    }
10750
10751    private InstallArgs createInstallArgs(InstallParams params) {
10752        if (params.move != null) {
10753            return new MoveInstallArgs(params);
10754        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10755            return new AsecInstallArgs(params);
10756        } else {
10757            return new FileInstallArgs(params);
10758        }
10759    }
10760
10761    /**
10762     * Create args that describe an existing installed package. Typically used
10763     * when cleaning up old installs, or used as a move source.
10764     */
10765    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10766            String resourcePath, String[] instructionSets) {
10767        final boolean isInAsec;
10768        if (installOnExternalAsec(installFlags)) {
10769            /* Apps on SD card are always in ASEC containers. */
10770            isInAsec = true;
10771        } else if (installForwardLocked(installFlags)
10772                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10773            /*
10774             * Forward-locked apps are only in ASEC containers if they're the
10775             * new style
10776             */
10777            isInAsec = true;
10778        } else {
10779            isInAsec = false;
10780        }
10781
10782        if (isInAsec) {
10783            return new AsecInstallArgs(codePath, instructionSets,
10784                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10785        } else {
10786            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10787        }
10788    }
10789
10790    static abstract class InstallArgs {
10791        /** @see InstallParams#origin */
10792        final OriginInfo origin;
10793        /** @see InstallParams#move */
10794        final MoveInfo move;
10795
10796        final IPackageInstallObserver2 observer;
10797        // Always refers to PackageManager flags only
10798        final int installFlags;
10799        final String installerPackageName;
10800        final String volumeUuid;
10801        final ManifestDigest manifestDigest;
10802        final UserHandle user;
10803        final String abiOverride;
10804        final String[] installGrantPermissions;
10805
10806        // The list of instruction sets supported by this app. This is currently
10807        // only used during the rmdex() phase to clean up resources. We can get rid of this
10808        // if we move dex files under the common app path.
10809        /* nullable */ String[] instructionSets;
10810
10811        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10812                int installFlags, String installerPackageName, String volumeUuid,
10813                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10814                String abiOverride, String[] installGrantPermissions) {
10815            this.origin = origin;
10816            this.move = move;
10817            this.installFlags = installFlags;
10818            this.observer = observer;
10819            this.installerPackageName = installerPackageName;
10820            this.volumeUuid = volumeUuid;
10821            this.manifestDigest = manifestDigest;
10822            this.user = user;
10823            this.instructionSets = instructionSets;
10824            this.abiOverride = abiOverride;
10825            this.installGrantPermissions = installGrantPermissions;
10826        }
10827
10828        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10829        abstract int doPreInstall(int status);
10830
10831        /**
10832         * Rename package into final resting place. All paths on the given
10833         * scanned package should be updated to reflect the rename.
10834         */
10835        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10836        abstract int doPostInstall(int status, int uid);
10837
10838        /** @see PackageSettingBase#codePathString */
10839        abstract String getCodePath();
10840        /** @see PackageSettingBase#resourcePathString */
10841        abstract String getResourcePath();
10842
10843        // Need installer lock especially for dex file removal.
10844        abstract void cleanUpResourcesLI();
10845        abstract boolean doPostDeleteLI(boolean delete);
10846
10847        /**
10848         * Called before the source arguments are copied. This is used mostly
10849         * for MoveParams when it needs to read the source file to put it in the
10850         * destination.
10851         */
10852        int doPreCopy() {
10853            return PackageManager.INSTALL_SUCCEEDED;
10854        }
10855
10856        /**
10857         * Called after the source arguments are copied. This is used mostly for
10858         * MoveParams when it needs to read the source file to put it in the
10859         * destination.
10860         *
10861         * @return
10862         */
10863        int doPostCopy(int uid) {
10864            return PackageManager.INSTALL_SUCCEEDED;
10865        }
10866
10867        protected boolean isFwdLocked() {
10868            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10869        }
10870
10871        protected boolean isExternalAsec() {
10872            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10873        }
10874
10875        UserHandle getUser() {
10876            return user;
10877        }
10878    }
10879
10880    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10881        if (!allCodePaths.isEmpty()) {
10882            if (instructionSets == null) {
10883                throw new IllegalStateException("instructionSet == null");
10884            }
10885            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10886            for (String codePath : allCodePaths) {
10887                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10888                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10889                    if (retCode < 0) {
10890                        Slog.w(TAG, "Couldn't remove dex file for package: "
10891                                + " at location " + codePath + ", retcode=" + retCode);
10892                        // we don't consider this to be a failure of the core package deletion
10893                    }
10894                }
10895            }
10896        }
10897    }
10898
10899    /**
10900     * Logic to handle installation of non-ASEC applications, including copying
10901     * and renaming logic.
10902     */
10903    class FileInstallArgs extends InstallArgs {
10904        private File codeFile;
10905        private File resourceFile;
10906
10907        // Example topology:
10908        // /data/app/com.example/base.apk
10909        // /data/app/com.example/split_foo.apk
10910        // /data/app/com.example/lib/arm/libfoo.so
10911        // /data/app/com.example/lib/arm64/libfoo.so
10912        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10913
10914        /** New install */
10915        FileInstallArgs(InstallParams params) {
10916            super(params.origin, params.move, params.observer, params.installFlags,
10917                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10918                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10919                    params.grantedRuntimePermissions);
10920            if (isFwdLocked()) {
10921                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10922            }
10923        }
10924
10925        /** Existing install */
10926        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10927            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10928                    null, null);
10929            this.codeFile = (codePath != null) ? new File(codePath) : null;
10930            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10931        }
10932
10933        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10934            if (origin.staged) {
10935                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10936                codeFile = origin.file;
10937                resourceFile = origin.file;
10938                return PackageManager.INSTALL_SUCCEEDED;
10939            }
10940
10941            try {
10942                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10943                codeFile = tempDir;
10944                resourceFile = tempDir;
10945            } catch (IOException e) {
10946                Slog.w(TAG, "Failed to create copy file: " + e);
10947                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10948            }
10949
10950            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10951                @Override
10952                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10953                    if (!FileUtils.isValidExtFilename(name)) {
10954                        throw new IllegalArgumentException("Invalid filename: " + name);
10955                    }
10956                    try {
10957                        final File file = new File(codeFile, name);
10958                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10959                                O_RDWR | O_CREAT, 0644);
10960                        Os.chmod(file.getAbsolutePath(), 0644);
10961                        return new ParcelFileDescriptor(fd);
10962                    } catch (ErrnoException e) {
10963                        throw new RemoteException("Failed to open: " + e.getMessage());
10964                    }
10965                }
10966            };
10967
10968            int ret = PackageManager.INSTALL_SUCCEEDED;
10969            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10970            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10971                Slog.e(TAG, "Failed to copy package");
10972                return ret;
10973            }
10974
10975            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10976            NativeLibraryHelper.Handle handle = null;
10977            try {
10978                handle = NativeLibraryHelper.Handle.create(codeFile);
10979                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10980                        abiOverride);
10981            } catch (IOException e) {
10982                Slog.e(TAG, "Copying native libraries failed", e);
10983                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10984            } finally {
10985                IoUtils.closeQuietly(handle);
10986            }
10987
10988            return ret;
10989        }
10990
10991        int doPreInstall(int status) {
10992            if (status != PackageManager.INSTALL_SUCCEEDED) {
10993                cleanUp();
10994            }
10995            return status;
10996        }
10997
10998        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10999            if (status != PackageManager.INSTALL_SUCCEEDED) {
11000                cleanUp();
11001                return false;
11002            }
11003
11004            final File targetDir = codeFile.getParentFile();
11005            final File beforeCodeFile = codeFile;
11006            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11007
11008            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11009            try {
11010                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11011            } catch (ErrnoException e) {
11012                Slog.w(TAG, "Failed to rename", e);
11013                return false;
11014            }
11015
11016            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11017                Slog.w(TAG, "Failed to restorecon");
11018                return false;
11019            }
11020
11021            // Reflect the rename internally
11022            codeFile = afterCodeFile;
11023            resourceFile = afterCodeFile;
11024
11025            // Reflect the rename in scanned details
11026            pkg.codePath = afterCodeFile.getAbsolutePath();
11027            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11028                    pkg.baseCodePath);
11029            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11030                    pkg.splitCodePaths);
11031
11032            // Reflect the rename in app info
11033            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11034            pkg.applicationInfo.setCodePath(pkg.codePath);
11035            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11036            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11037            pkg.applicationInfo.setResourcePath(pkg.codePath);
11038            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11039            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11040
11041            return true;
11042        }
11043
11044        int doPostInstall(int status, int uid) {
11045            if (status != PackageManager.INSTALL_SUCCEEDED) {
11046                cleanUp();
11047            }
11048            return status;
11049        }
11050
11051        @Override
11052        String getCodePath() {
11053            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11054        }
11055
11056        @Override
11057        String getResourcePath() {
11058            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11059        }
11060
11061        private boolean cleanUp() {
11062            if (codeFile == null || !codeFile.exists()) {
11063                return false;
11064            }
11065
11066            if (codeFile.isDirectory()) {
11067                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11068            } else {
11069                codeFile.delete();
11070            }
11071
11072            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11073                resourceFile.delete();
11074            }
11075
11076            return true;
11077        }
11078
11079        void cleanUpResourcesLI() {
11080            // Try enumerating all code paths before deleting
11081            List<String> allCodePaths = Collections.EMPTY_LIST;
11082            if (codeFile != null && codeFile.exists()) {
11083                try {
11084                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11085                    allCodePaths = pkg.getAllCodePaths();
11086                } catch (PackageParserException e) {
11087                    // Ignored; we tried our best
11088                }
11089            }
11090
11091            cleanUp();
11092            removeDexFiles(allCodePaths, instructionSets);
11093        }
11094
11095        boolean doPostDeleteLI(boolean delete) {
11096            // XXX err, shouldn't we respect the delete flag?
11097            cleanUpResourcesLI();
11098            return true;
11099        }
11100    }
11101
11102    private boolean isAsecExternal(String cid) {
11103        final String asecPath = PackageHelper.getSdFilesystem(cid);
11104        return !asecPath.startsWith(mAsecInternalPath);
11105    }
11106
11107    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11108            PackageManagerException {
11109        if (copyRet < 0) {
11110            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11111                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11112                throw new PackageManagerException(copyRet, message);
11113            }
11114        }
11115    }
11116
11117    /**
11118     * Extract the MountService "container ID" from the full code path of an
11119     * .apk.
11120     */
11121    static String cidFromCodePath(String fullCodePath) {
11122        int eidx = fullCodePath.lastIndexOf("/");
11123        String subStr1 = fullCodePath.substring(0, eidx);
11124        int sidx = subStr1.lastIndexOf("/");
11125        return subStr1.substring(sidx+1, eidx);
11126    }
11127
11128    /**
11129     * Logic to handle installation of ASEC applications, including copying and
11130     * renaming logic.
11131     */
11132    class AsecInstallArgs extends InstallArgs {
11133        static final String RES_FILE_NAME = "pkg.apk";
11134        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11135
11136        String cid;
11137        String packagePath;
11138        String resourcePath;
11139
11140        /** New install */
11141        AsecInstallArgs(InstallParams params) {
11142            super(params.origin, params.move, params.observer, params.installFlags,
11143                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11144                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11145                    params.grantedRuntimePermissions);
11146        }
11147
11148        /** Existing install */
11149        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11150                        boolean isExternal, boolean isForwardLocked) {
11151            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11152                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11153                    instructionSets, null, null);
11154            // Hackily pretend we're still looking at a full code path
11155            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11156                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11157            }
11158
11159            // Extract cid from fullCodePath
11160            int eidx = fullCodePath.lastIndexOf("/");
11161            String subStr1 = fullCodePath.substring(0, eidx);
11162            int sidx = subStr1.lastIndexOf("/");
11163            cid = subStr1.substring(sidx+1, eidx);
11164            setMountPath(subStr1);
11165        }
11166
11167        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11168            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11169                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11170                    instructionSets, null, null);
11171            this.cid = cid;
11172            setMountPath(PackageHelper.getSdDir(cid));
11173        }
11174
11175        void createCopyFile() {
11176            cid = mInstallerService.allocateExternalStageCidLegacy();
11177        }
11178
11179        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11180            if (origin.staged) {
11181                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11182                cid = origin.cid;
11183                setMountPath(PackageHelper.getSdDir(cid));
11184                return PackageManager.INSTALL_SUCCEEDED;
11185            }
11186
11187            if (temp) {
11188                createCopyFile();
11189            } else {
11190                /*
11191                 * Pre-emptively destroy the container since it's destroyed if
11192                 * copying fails due to it existing anyway.
11193                 */
11194                PackageHelper.destroySdDir(cid);
11195            }
11196
11197            final String newMountPath = imcs.copyPackageToContainer(
11198                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11199                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11200
11201            if (newMountPath != null) {
11202                setMountPath(newMountPath);
11203                return PackageManager.INSTALL_SUCCEEDED;
11204            } else {
11205                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11206            }
11207        }
11208
11209        @Override
11210        String getCodePath() {
11211            return packagePath;
11212        }
11213
11214        @Override
11215        String getResourcePath() {
11216            return resourcePath;
11217        }
11218
11219        int doPreInstall(int status) {
11220            if (status != PackageManager.INSTALL_SUCCEEDED) {
11221                // Destroy container
11222                PackageHelper.destroySdDir(cid);
11223            } else {
11224                boolean mounted = PackageHelper.isContainerMounted(cid);
11225                if (!mounted) {
11226                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11227                            Process.SYSTEM_UID);
11228                    if (newMountPath != null) {
11229                        setMountPath(newMountPath);
11230                    } else {
11231                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11232                    }
11233                }
11234            }
11235            return status;
11236        }
11237
11238        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11239            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11240            String newMountPath = null;
11241            if (PackageHelper.isContainerMounted(cid)) {
11242                // Unmount the container
11243                if (!PackageHelper.unMountSdDir(cid)) {
11244                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11245                    return false;
11246                }
11247            }
11248            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11249                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11250                        " which might be stale. Will try to clean up.");
11251                // Clean up the stale container and proceed to recreate.
11252                if (!PackageHelper.destroySdDir(newCacheId)) {
11253                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11254                    return false;
11255                }
11256                // Successfully cleaned up stale container. Try to rename again.
11257                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11258                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11259                            + " inspite of cleaning it up.");
11260                    return false;
11261                }
11262            }
11263            if (!PackageHelper.isContainerMounted(newCacheId)) {
11264                Slog.w(TAG, "Mounting container " + newCacheId);
11265                newMountPath = PackageHelper.mountSdDir(newCacheId,
11266                        getEncryptKey(), Process.SYSTEM_UID);
11267            } else {
11268                newMountPath = PackageHelper.getSdDir(newCacheId);
11269            }
11270            if (newMountPath == null) {
11271                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11272                return false;
11273            }
11274            Log.i(TAG, "Succesfully renamed " + cid +
11275                    " to " + newCacheId +
11276                    " at new path: " + newMountPath);
11277            cid = newCacheId;
11278
11279            final File beforeCodeFile = new File(packagePath);
11280            setMountPath(newMountPath);
11281            final File afterCodeFile = new File(packagePath);
11282
11283            // Reflect the rename in scanned details
11284            pkg.codePath = afterCodeFile.getAbsolutePath();
11285            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11286                    pkg.baseCodePath);
11287            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11288                    pkg.splitCodePaths);
11289
11290            // Reflect the rename in app info
11291            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11292            pkg.applicationInfo.setCodePath(pkg.codePath);
11293            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11294            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11295            pkg.applicationInfo.setResourcePath(pkg.codePath);
11296            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11297            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11298
11299            return true;
11300        }
11301
11302        private void setMountPath(String mountPath) {
11303            final File mountFile = new File(mountPath);
11304
11305            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11306            if (monolithicFile.exists()) {
11307                packagePath = monolithicFile.getAbsolutePath();
11308                if (isFwdLocked()) {
11309                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11310                } else {
11311                    resourcePath = packagePath;
11312                }
11313            } else {
11314                packagePath = mountFile.getAbsolutePath();
11315                resourcePath = packagePath;
11316            }
11317        }
11318
11319        int doPostInstall(int status, int uid) {
11320            if (status != PackageManager.INSTALL_SUCCEEDED) {
11321                cleanUp();
11322            } else {
11323                final int groupOwner;
11324                final String protectedFile;
11325                if (isFwdLocked()) {
11326                    groupOwner = UserHandle.getSharedAppGid(uid);
11327                    protectedFile = RES_FILE_NAME;
11328                } else {
11329                    groupOwner = -1;
11330                    protectedFile = null;
11331                }
11332
11333                if (uid < Process.FIRST_APPLICATION_UID
11334                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11335                    Slog.e(TAG, "Failed to finalize " + cid);
11336                    PackageHelper.destroySdDir(cid);
11337                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11338                }
11339
11340                boolean mounted = PackageHelper.isContainerMounted(cid);
11341                if (!mounted) {
11342                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11343                }
11344            }
11345            return status;
11346        }
11347
11348        private void cleanUp() {
11349            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11350
11351            // Destroy secure container
11352            PackageHelper.destroySdDir(cid);
11353        }
11354
11355        private List<String> getAllCodePaths() {
11356            final File codeFile = new File(getCodePath());
11357            if (codeFile != null && codeFile.exists()) {
11358                try {
11359                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11360                    return pkg.getAllCodePaths();
11361                } catch (PackageParserException e) {
11362                    // Ignored; we tried our best
11363                }
11364            }
11365            return Collections.EMPTY_LIST;
11366        }
11367
11368        void cleanUpResourcesLI() {
11369            // Enumerate all code paths before deleting
11370            cleanUpResourcesLI(getAllCodePaths());
11371        }
11372
11373        private void cleanUpResourcesLI(List<String> allCodePaths) {
11374            cleanUp();
11375            removeDexFiles(allCodePaths, instructionSets);
11376        }
11377
11378        String getPackageName() {
11379            return getAsecPackageName(cid);
11380        }
11381
11382        boolean doPostDeleteLI(boolean delete) {
11383            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11384            final List<String> allCodePaths = getAllCodePaths();
11385            boolean mounted = PackageHelper.isContainerMounted(cid);
11386            if (mounted) {
11387                // Unmount first
11388                if (PackageHelper.unMountSdDir(cid)) {
11389                    mounted = false;
11390                }
11391            }
11392            if (!mounted && delete) {
11393                cleanUpResourcesLI(allCodePaths);
11394            }
11395            return !mounted;
11396        }
11397
11398        @Override
11399        int doPreCopy() {
11400            if (isFwdLocked()) {
11401                if (!PackageHelper.fixSdPermissions(cid,
11402                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11403                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11404                }
11405            }
11406
11407            return PackageManager.INSTALL_SUCCEEDED;
11408        }
11409
11410        @Override
11411        int doPostCopy(int uid) {
11412            if (isFwdLocked()) {
11413                if (uid < Process.FIRST_APPLICATION_UID
11414                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11415                                RES_FILE_NAME)) {
11416                    Slog.e(TAG, "Failed to finalize " + cid);
11417                    PackageHelper.destroySdDir(cid);
11418                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11419                }
11420            }
11421
11422            return PackageManager.INSTALL_SUCCEEDED;
11423        }
11424    }
11425
11426    /**
11427     * Logic to handle movement of existing installed applications.
11428     */
11429    class MoveInstallArgs extends InstallArgs {
11430        private File codeFile;
11431        private File resourceFile;
11432
11433        /** New install */
11434        MoveInstallArgs(InstallParams params) {
11435            super(params.origin, params.move, params.observer, params.installFlags,
11436                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11437                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11438                    params.grantedRuntimePermissions);
11439        }
11440
11441        int copyApk(IMediaContainerService imcs, boolean temp) {
11442            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11443                    + move.fromUuid + " to " + move.toUuid);
11444            synchronized (mInstaller) {
11445                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11446                        move.dataAppName, move.appId, move.seinfo) != 0) {
11447                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11448                }
11449            }
11450
11451            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11452            resourceFile = codeFile;
11453            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11454
11455            return PackageManager.INSTALL_SUCCEEDED;
11456        }
11457
11458        int doPreInstall(int status) {
11459            if (status != PackageManager.INSTALL_SUCCEEDED) {
11460                cleanUp(move.toUuid);
11461            }
11462            return status;
11463        }
11464
11465        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11466            if (status != PackageManager.INSTALL_SUCCEEDED) {
11467                cleanUp(move.toUuid);
11468                return false;
11469            }
11470
11471            // Reflect the move in app info
11472            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11473            pkg.applicationInfo.setCodePath(pkg.codePath);
11474            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11475            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11476            pkg.applicationInfo.setResourcePath(pkg.codePath);
11477            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11478            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11479
11480            return true;
11481        }
11482
11483        int doPostInstall(int status, int uid) {
11484            if (status == PackageManager.INSTALL_SUCCEEDED) {
11485                cleanUp(move.fromUuid);
11486            } else {
11487                cleanUp(move.toUuid);
11488            }
11489            return status;
11490        }
11491
11492        @Override
11493        String getCodePath() {
11494            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11495        }
11496
11497        @Override
11498        String getResourcePath() {
11499            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11500        }
11501
11502        private boolean cleanUp(String volumeUuid) {
11503            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11504                    move.dataAppName);
11505            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11506            synchronized (mInstallLock) {
11507                // Clean up both app data and code
11508                removeDataDirsLI(volumeUuid, move.packageName);
11509                if (codeFile.isDirectory()) {
11510                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11511                } else {
11512                    codeFile.delete();
11513                }
11514            }
11515            return true;
11516        }
11517
11518        void cleanUpResourcesLI() {
11519            throw new UnsupportedOperationException();
11520        }
11521
11522        boolean doPostDeleteLI(boolean delete) {
11523            throw new UnsupportedOperationException();
11524        }
11525    }
11526
11527    static String getAsecPackageName(String packageCid) {
11528        int idx = packageCid.lastIndexOf("-");
11529        if (idx == -1) {
11530            return packageCid;
11531        }
11532        return packageCid.substring(0, idx);
11533    }
11534
11535    // Utility method used to create code paths based on package name and available index.
11536    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11537        String idxStr = "";
11538        int idx = 1;
11539        // Fall back to default value of idx=1 if prefix is not
11540        // part of oldCodePath
11541        if (oldCodePath != null) {
11542            String subStr = oldCodePath;
11543            // Drop the suffix right away
11544            if (suffix != null && subStr.endsWith(suffix)) {
11545                subStr = subStr.substring(0, subStr.length() - suffix.length());
11546            }
11547            // If oldCodePath already contains prefix find out the
11548            // ending index to either increment or decrement.
11549            int sidx = subStr.lastIndexOf(prefix);
11550            if (sidx != -1) {
11551                subStr = subStr.substring(sidx + prefix.length());
11552                if (subStr != null) {
11553                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11554                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11555                    }
11556                    try {
11557                        idx = Integer.parseInt(subStr);
11558                        if (idx <= 1) {
11559                            idx++;
11560                        } else {
11561                            idx--;
11562                        }
11563                    } catch(NumberFormatException e) {
11564                    }
11565                }
11566            }
11567        }
11568        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11569        return prefix + idxStr;
11570    }
11571
11572    private File getNextCodePath(File targetDir, String packageName) {
11573        int suffix = 1;
11574        File result;
11575        do {
11576            result = new File(targetDir, packageName + "-" + suffix);
11577            suffix++;
11578        } while (result.exists());
11579        return result;
11580    }
11581
11582    // Utility method that returns the relative package path with respect
11583    // to the installation directory. Like say for /data/data/com.test-1.apk
11584    // string com.test-1 is returned.
11585    static String deriveCodePathName(String codePath) {
11586        if (codePath == null) {
11587            return null;
11588        }
11589        final File codeFile = new File(codePath);
11590        final String name = codeFile.getName();
11591        if (codeFile.isDirectory()) {
11592            return name;
11593        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11594            final int lastDot = name.lastIndexOf('.');
11595            return name.substring(0, lastDot);
11596        } else {
11597            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11598            return null;
11599        }
11600    }
11601
11602    class PackageInstalledInfo {
11603        String name;
11604        int uid;
11605        // The set of users that originally had this package installed.
11606        int[] origUsers;
11607        // The set of users that now have this package installed.
11608        int[] newUsers;
11609        PackageParser.Package pkg;
11610        int returnCode;
11611        String returnMsg;
11612        PackageRemovedInfo removedInfo;
11613
11614        public void setError(int code, String msg) {
11615            returnCode = code;
11616            returnMsg = msg;
11617            Slog.w(TAG, msg);
11618        }
11619
11620        public void setError(String msg, PackageParserException e) {
11621            returnCode = e.error;
11622            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11623            Slog.w(TAG, msg, e);
11624        }
11625
11626        public void setError(String msg, PackageManagerException e) {
11627            returnCode = e.error;
11628            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11629            Slog.w(TAG, msg, e);
11630        }
11631
11632        // In some error cases we want to convey more info back to the observer
11633        String origPackage;
11634        String origPermission;
11635    }
11636
11637    /*
11638     * Install a non-existing package.
11639     */
11640    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11641            UserHandle user, String installerPackageName, String volumeUuid,
11642            PackageInstalledInfo res) {
11643        // Remember this for later, in case we need to rollback this install
11644        String pkgName = pkg.packageName;
11645
11646        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11647        final boolean dataDirExists = Environment
11648                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11649        synchronized(mPackages) {
11650            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11651                // A package with the same name is already installed, though
11652                // it has been renamed to an older name.  The package we
11653                // are trying to install should be installed as an update to
11654                // the existing one, but that has not been requested, so bail.
11655                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11656                        + " without first uninstalling package running as "
11657                        + mSettings.mRenamedPackages.get(pkgName));
11658                return;
11659            }
11660            if (mPackages.containsKey(pkgName)) {
11661                // Don't allow installation over an existing package with the same name.
11662                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11663                        + " without first uninstalling.");
11664                return;
11665            }
11666        }
11667
11668        try {
11669            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11670                    System.currentTimeMillis(), user);
11671
11672            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11673            // delete the partially installed application. the data directory will have to be
11674            // restored if it was already existing
11675            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11676                // remove package from internal structures.  Note that we want deletePackageX to
11677                // delete the package data and cache directories that it created in
11678                // scanPackageLocked, unless those directories existed before we even tried to
11679                // install.
11680                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11681                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11682                                res.removedInfo, true);
11683            }
11684
11685        } catch (PackageManagerException e) {
11686            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11687        }
11688    }
11689
11690    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11691        // Can't rotate keys during boot or if sharedUser.
11692        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11693                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11694            return false;
11695        }
11696        // app is using upgradeKeySets; make sure all are valid
11697        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11698        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11699        for (int i = 0; i < upgradeKeySets.length; i++) {
11700            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11701                Slog.wtf(TAG, "Package "
11702                         + (oldPs.name != null ? oldPs.name : "<null>")
11703                         + " contains upgrade-key-set reference to unknown key-set: "
11704                         + upgradeKeySets[i]
11705                         + " reverting to signatures check.");
11706                return false;
11707            }
11708        }
11709        return true;
11710    }
11711
11712    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11713        // Upgrade keysets are being used.  Determine if new package has a superset of the
11714        // required keys.
11715        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11716        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11717        for (int i = 0; i < upgradeKeySets.length; i++) {
11718            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11719            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11720                return true;
11721            }
11722        }
11723        return false;
11724    }
11725
11726    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11727            UserHandle user, String installerPackageName, String volumeUuid,
11728            PackageInstalledInfo res) {
11729        final PackageParser.Package oldPackage;
11730        final String pkgName = pkg.packageName;
11731        final int[] allUsers;
11732        final boolean[] perUserInstalled;
11733        final boolean weFroze;
11734
11735        // First find the old package info and check signatures
11736        synchronized(mPackages) {
11737            oldPackage = mPackages.get(pkgName);
11738            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11739            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11740            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11741                if(!checkUpgradeKeySetLP(ps, pkg)) {
11742                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11743                            "New package not signed by keys specified by upgrade-keysets: "
11744                            + pkgName);
11745                    return;
11746                }
11747            } else {
11748                // default to original signature matching
11749                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11750                    != PackageManager.SIGNATURE_MATCH) {
11751                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11752                            "New package has a different signature: " + pkgName);
11753                    return;
11754                }
11755            }
11756
11757            // In case of rollback, remember per-user/profile install state
11758            allUsers = sUserManager.getUserIds();
11759            perUserInstalled = new boolean[allUsers.length];
11760            for (int i = 0; i < allUsers.length; i++) {
11761                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11762            }
11763
11764            // Mark the app as frozen to prevent launching during the upgrade
11765            // process, and then kill all running instances
11766            if (!ps.frozen) {
11767                ps.frozen = true;
11768                weFroze = true;
11769            } else {
11770                weFroze = false;
11771            }
11772        }
11773
11774        // Now that we're guarded by frozen state, kill app during upgrade
11775        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11776
11777        try {
11778            boolean sysPkg = (isSystemApp(oldPackage));
11779            if (sysPkg) {
11780                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11781                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11782            } else {
11783                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11784                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11785            }
11786        } finally {
11787            // Regardless of success or failure of upgrade steps above, always
11788            // unfreeze the package if we froze it
11789            if (weFroze) {
11790                unfreezePackage(pkgName);
11791            }
11792        }
11793    }
11794
11795    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11796            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11797            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11798            String volumeUuid, PackageInstalledInfo res) {
11799        String pkgName = deletedPackage.packageName;
11800        boolean deletedPkg = true;
11801        boolean updatedSettings = false;
11802
11803        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11804                + deletedPackage);
11805        long origUpdateTime;
11806        if (pkg.mExtras != null) {
11807            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11808        } else {
11809            origUpdateTime = 0;
11810        }
11811
11812        // First delete the existing package while retaining the data directory
11813        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11814                res.removedInfo, true)) {
11815            // If the existing package wasn't successfully deleted
11816            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11817            deletedPkg = false;
11818        } else {
11819            // Successfully deleted the old package; proceed with replace.
11820
11821            // If deleted package lived in a container, give users a chance to
11822            // relinquish resources before killing.
11823            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11824                if (DEBUG_INSTALL) {
11825                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11826                }
11827                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11828                final ArrayList<String> pkgList = new ArrayList<String>(1);
11829                pkgList.add(deletedPackage.applicationInfo.packageName);
11830                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11831            }
11832
11833            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11834            try {
11835                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11836                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11837                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11838                        perUserInstalled, res, user);
11839                updatedSettings = true;
11840            } catch (PackageManagerException e) {
11841                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11842            }
11843        }
11844
11845        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11846            // remove package from internal structures.  Note that we want deletePackageX to
11847            // delete the package data and cache directories that it created in
11848            // scanPackageLocked, unless those directories existed before we even tried to
11849            // install.
11850            if(updatedSettings) {
11851                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11852                deletePackageLI(
11853                        pkgName, null, true, allUsers, perUserInstalled,
11854                        PackageManager.DELETE_KEEP_DATA,
11855                                res.removedInfo, true);
11856            }
11857            // Since we failed to install the new package we need to restore the old
11858            // package that we deleted.
11859            if (deletedPkg) {
11860                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11861                File restoreFile = new File(deletedPackage.codePath);
11862                // Parse old package
11863                boolean oldExternal = isExternal(deletedPackage);
11864                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11865                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11866                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11867                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11868                try {
11869                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11870                } catch (PackageManagerException e) {
11871                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11872                            + e.getMessage());
11873                    return;
11874                }
11875                // Restore of old package succeeded. Update permissions.
11876                // writer
11877                synchronized (mPackages) {
11878                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11879                            UPDATE_PERMISSIONS_ALL);
11880                    // can downgrade to reader
11881                    mSettings.writeLPr();
11882                }
11883                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11884            }
11885        }
11886    }
11887
11888    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11889            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11890            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11891            String volumeUuid, PackageInstalledInfo res) {
11892        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11893                + ", old=" + deletedPackage);
11894        boolean disabledSystem = false;
11895        boolean updatedSettings = false;
11896        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11897        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11898                != 0) {
11899            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11900        }
11901        String packageName = deletedPackage.packageName;
11902        if (packageName == null) {
11903            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11904                    "Attempt to delete null packageName.");
11905            return;
11906        }
11907        PackageParser.Package oldPkg;
11908        PackageSetting oldPkgSetting;
11909        // reader
11910        synchronized (mPackages) {
11911            oldPkg = mPackages.get(packageName);
11912            oldPkgSetting = mSettings.mPackages.get(packageName);
11913            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11914                    (oldPkgSetting == null)) {
11915                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11916                        "Couldn't find package:" + packageName + " information");
11917                return;
11918            }
11919        }
11920
11921        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11922        res.removedInfo.removedPackage = packageName;
11923        // Remove existing system package
11924        removePackageLI(oldPkgSetting, true);
11925        // writer
11926        synchronized (mPackages) {
11927            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11928            if (!disabledSystem && deletedPackage != null) {
11929                // We didn't need to disable the .apk as a current system package,
11930                // which means we are replacing another update that is already
11931                // installed.  We need to make sure to delete the older one's .apk.
11932                res.removedInfo.args = createInstallArgsForExisting(0,
11933                        deletedPackage.applicationInfo.getCodePath(),
11934                        deletedPackage.applicationInfo.getResourcePath(),
11935                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11936            } else {
11937                res.removedInfo.args = null;
11938            }
11939        }
11940
11941        // Successfully disabled the old package. Now proceed with re-installation
11942        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11943
11944        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11945        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11946
11947        PackageParser.Package newPackage = null;
11948        try {
11949            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11950            if (newPackage.mExtras != null) {
11951                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11952                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11953                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11954
11955                // is the update attempting to change shared user? that isn't going to work...
11956                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11957                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11958                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11959                            + " to " + newPkgSetting.sharedUser);
11960                    updatedSettings = true;
11961                }
11962            }
11963
11964            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11965                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11966                        perUserInstalled, res, user);
11967                updatedSettings = true;
11968            }
11969
11970        } catch (PackageManagerException e) {
11971            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11972        }
11973
11974        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11975            // Re installation failed. Restore old information
11976            // Remove new pkg information
11977            if (newPackage != null) {
11978                removeInstalledPackageLI(newPackage, true);
11979            }
11980            // Add back the old system package
11981            try {
11982                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11983            } catch (PackageManagerException e) {
11984                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11985            }
11986            // Restore the old system information in Settings
11987            synchronized (mPackages) {
11988                if (disabledSystem) {
11989                    mSettings.enableSystemPackageLPw(packageName);
11990                }
11991                if (updatedSettings) {
11992                    mSettings.setInstallerPackageName(packageName,
11993                            oldPkgSetting.installerPackageName);
11994                }
11995                mSettings.writeLPr();
11996            }
11997        }
11998    }
11999
12000    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12001            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12002            UserHandle user) {
12003        String pkgName = newPackage.packageName;
12004        synchronized (mPackages) {
12005            //write settings. the installStatus will be incomplete at this stage.
12006            //note that the new package setting would have already been
12007            //added to mPackages. It hasn't been persisted yet.
12008            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12009            mSettings.writeLPr();
12010        }
12011
12012        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12013
12014        synchronized (mPackages) {
12015            updatePermissionsLPw(newPackage.packageName, newPackage,
12016                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12017                            ? UPDATE_PERMISSIONS_ALL : 0));
12018            // For system-bundled packages, we assume that installing an upgraded version
12019            // of the package implies that the user actually wants to run that new code,
12020            // so we enable the package.
12021            PackageSetting ps = mSettings.mPackages.get(pkgName);
12022            if (ps != null) {
12023                if (isSystemApp(newPackage)) {
12024                    // NB: implicit assumption that system package upgrades apply to all users
12025                    if (DEBUG_INSTALL) {
12026                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12027                    }
12028                    if (res.origUsers != null) {
12029                        for (int userHandle : res.origUsers) {
12030                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12031                                    userHandle, installerPackageName);
12032                        }
12033                    }
12034                    // Also convey the prior install/uninstall state
12035                    if (allUsers != null && perUserInstalled != null) {
12036                        for (int i = 0; i < allUsers.length; i++) {
12037                            if (DEBUG_INSTALL) {
12038                                Slog.d(TAG, "    user " + allUsers[i]
12039                                        + " => " + perUserInstalled[i]);
12040                            }
12041                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12042                        }
12043                        // these install state changes will be persisted in the
12044                        // upcoming call to mSettings.writeLPr().
12045                    }
12046                }
12047                // It's implied that when a user requests installation, they want the app to be
12048                // installed and enabled.
12049                int userId = user.getIdentifier();
12050                if (userId != UserHandle.USER_ALL) {
12051                    ps.setInstalled(true, userId);
12052                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12053                }
12054            }
12055            res.name = pkgName;
12056            res.uid = newPackage.applicationInfo.uid;
12057            res.pkg = newPackage;
12058            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12059            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12060            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12061            //to update install status
12062            mSettings.writeLPr();
12063        }
12064    }
12065
12066    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12067        final int installFlags = args.installFlags;
12068        final String installerPackageName = args.installerPackageName;
12069        final String volumeUuid = args.volumeUuid;
12070        final File tmpPackageFile = new File(args.getCodePath());
12071        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12072        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12073                || (args.volumeUuid != null));
12074        boolean replace = false;
12075        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12076        if (args.move != null) {
12077            // moving a complete application; perfom an initial scan on the new install location
12078            scanFlags |= SCAN_INITIAL;
12079        }
12080        // Result object to be returned
12081        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12082
12083        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12084        // Retrieve PackageSettings and parse package
12085        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12086                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12087                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12088        PackageParser pp = new PackageParser();
12089        pp.setSeparateProcesses(mSeparateProcesses);
12090        pp.setDisplayMetrics(mMetrics);
12091
12092        final PackageParser.Package pkg;
12093        try {
12094            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12095        } catch (PackageParserException e) {
12096            res.setError("Failed parse during installPackageLI", e);
12097            return;
12098        }
12099
12100        // Mark that we have an install time CPU ABI override.
12101        pkg.cpuAbiOverride = args.abiOverride;
12102
12103        String pkgName = res.name = pkg.packageName;
12104        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12105            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12106                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12107                return;
12108            }
12109        }
12110
12111        try {
12112            pp.collectCertificates(pkg, parseFlags);
12113            pp.collectManifestDigest(pkg);
12114        } catch (PackageParserException e) {
12115            res.setError("Failed collect during installPackageLI", e);
12116            return;
12117        }
12118
12119        /* If the installer passed in a manifest digest, compare it now. */
12120        if (args.manifestDigest != null) {
12121            if (DEBUG_INSTALL) {
12122                final String parsedManifest = pkg.manifestDigest == null ? "null"
12123                        : pkg.manifestDigest.toString();
12124                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12125                        + parsedManifest);
12126            }
12127
12128            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12129                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12130                return;
12131            }
12132        } else if (DEBUG_INSTALL) {
12133            final String parsedManifest = pkg.manifestDigest == null
12134                    ? "null" : pkg.manifestDigest.toString();
12135            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12136        }
12137
12138        // Get rid of all references to package scan path via parser.
12139        pp = null;
12140        String oldCodePath = null;
12141        boolean systemApp = false;
12142        synchronized (mPackages) {
12143            // Check if installing already existing package
12144            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12145                String oldName = mSettings.mRenamedPackages.get(pkgName);
12146                if (pkg.mOriginalPackages != null
12147                        && pkg.mOriginalPackages.contains(oldName)
12148                        && mPackages.containsKey(oldName)) {
12149                    // This package is derived from an original package,
12150                    // and this device has been updating from that original
12151                    // name.  We must continue using the original name, so
12152                    // rename the new package here.
12153                    pkg.setPackageName(oldName);
12154                    pkgName = pkg.packageName;
12155                    replace = true;
12156                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12157                            + oldName + " pkgName=" + pkgName);
12158                } else if (mPackages.containsKey(pkgName)) {
12159                    // This package, under its official name, already exists
12160                    // on the device; we should replace it.
12161                    replace = true;
12162                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12163                }
12164
12165                // Prevent apps opting out from runtime permissions
12166                if (replace) {
12167                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12168                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12169                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12170                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12171                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12172                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12173                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12174                                        + " doesn't support runtime permissions but the old"
12175                                        + " target SDK " + oldTargetSdk + " does.");
12176                        return;
12177                    }
12178                }
12179            }
12180
12181            PackageSetting ps = mSettings.mPackages.get(pkgName);
12182            if (ps != null) {
12183                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12184
12185                // Quick sanity check that we're signed correctly if updating;
12186                // we'll check this again later when scanning, but we want to
12187                // bail early here before tripping over redefined permissions.
12188                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12189                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12190                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12191                                + pkg.packageName + " upgrade keys do not match the "
12192                                + "previously installed version");
12193                        return;
12194                    }
12195                } else {
12196                    try {
12197                        verifySignaturesLP(ps, pkg);
12198                    } catch (PackageManagerException e) {
12199                        res.setError(e.error, e.getMessage());
12200                        return;
12201                    }
12202                }
12203
12204                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12205                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12206                    systemApp = (ps.pkg.applicationInfo.flags &
12207                            ApplicationInfo.FLAG_SYSTEM) != 0;
12208                }
12209                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12210            }
12211
12212            // Check whether the newly-scanned package wants to define an already-defined perm
12213            int N = pkg.permissions.size();
12214            for (int i = N-1; i >= 0; i--) {
12215                PackageParser.Permission perm = pkg.permissions.get(i);
12216                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12217                if (bp != null) {
12218                    // If the defining package is signed with our cert, it's okay.  This
12219                    // also includes the "updating the same package" case, of course.
12220                    // "updating same package" could also involve key-rotation.
12221                    final boolean sigsOk;
12222                    if (bp.sourcePackage.equals(pkg.packageName)
12223                            && (bp.packageSetting instanceof PackageSetting)
12224                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12225                                    scanFlags))) {
12226                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12227                    } else {
12228                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12229                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12230                    }
12231                    if (!sigsOk) {
12232                        // If the owning package is the system itself, we log but allow
12233                        // install to proceed; we fail the install on all other permission
12234                        // redefinitions.
12235                        if (!bp.sourcePackage.equals("android")) {
12236                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12237                                    + pkg.packageName + " attempting to redeclare permission "
12238                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12239                            res.origPermission = perm.info.name;
12240                            res.origPackage = bp.sourcePackage;
12241                            return;
12242                        } else {
12243                            Slog.w(TAG, "Package " + pkg.packageName
12244                                    + " attempting to redeclare system permission "
12245                                    + perm.info.name + "; ignoring new declaration");
12246                            pkg.permissions.remove(i);
12247                        }
12248                    }
12249                }
12250            }
12251
12252        }
12253
12254        if (systemApp && onExternal) {
12255            // Disable updates to system apps on sdcard
12256            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12257                    "Cannot install updates to system apps on sdcard");
12258            return;
12259        }
12260
12261        if (args.move != null) {
12262            // We did an in-place move, so dex is ready to roll
12263            scanFlags |= SCAN_NO_DEX;
12264            scanFlags |= SCAN_MOVE;
12265        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12266            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12267            scanFlags |= SCAN_NO_DEX;
12268
12269            try {
12270                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12271                        true /* extract libs */);
12272            } catch (PackageManagerException pme) {
12273                Slog.e(TAG, "Error deriving application ABI", pme);
12274                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12275                return;
12276            }
12277
12278            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12279            int result = mPackageDexOptimizer
12280                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12281                            false /* defer */, false /* inclDependencies */);
12282            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12283                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12284                return;
12285            }
12286        }
12287
12288        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12289            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12290            return;
12291        }
12292
12293        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12294
12295        if (replace) {
12296            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12297                    installerPackageName, volumeUuid, res);
12298        } else {
12299            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12300                    args.user, installerPackageName, volumeUuid, res);
12301        }
12302        synchronized (mPackages) {
12303            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12304            if (ps != null) {
12305                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12306            }
12307        }
12308    }
12309
12310    private void startIntentFilterVerifications(int userId, boolean replacing,
12311            PackageParser.Package pkg) {
12312        if (mIntentFilterVerifierComponent == null) {
12313            Slog.w(TAG, "No IntentFilter verification will not be done as "
12314                    + "there is no IntentFilterVerifier available!");
12315            return;
12316        }
12317
12318        final int verifierUid = getPackageUid(
12319                mIntentFilterVerifierComponent.getPackageName(),
12320                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12321
12322        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12323        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12324        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12325        mHandler.sendMessage(msg);
12326    }
12327
12328    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12329            PackageParser.Package pkg) {
12330        int size = pkg.activities.size();
12331        if (size == 0) {
12332            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12333                    "No activity, so no need to verify any IntentFilter!");
12334            return;
12335        }
12336
12337        final boolean hasDomainURLs = hasDomainURLs(pkg);
12338        if (!hasDomainURLs) {
12339            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12340                    "No domain URLs, so no need to verify any IntentFilter!");
12341            return;
12342        }
12343
12344        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12345                + " if any IntentFilter from the " + size
12346                + " Activities needs verification ...");
12347
12348        int count = 0;
12349        final String packageName = pkg.packageName;
12350
12351        synchronized (mPackages) {
12352            // If this is a new install and we see that we've already run verification for this
12353            // package, we have nothing to do: it means the state was restored from backup.
12354            if (!replacing) {
12355                IntentFilterVerificationInfo ivi =
12356                        mSettings.getIntentFilterVerificationLPr(packageName);
12357                if (ivi != null) {
12358                    if (DEBUG_DOMAIN_VERIFICATION) {
12359                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12360                                + ivi.getStatusString());
12361                    }
12362                    return;
12363                }
12364            }
12365
12366            // If any filters need to be verified, then all need to be.
12367            boolean needToVerify = false;
12368            for (PackageParser.Activity a : pkg.activities) {
12369                for (ActivityIntentInfo filter : a.intents) {
12370                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12371                        if (DEBUG_DOMAIN_VERIFICATION) {
12372                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12373                        }
12374                        needToVerify = true;
12375                        break;
12376                    }
12377                }
12378            }
12379
12380            if (needToVerify) {
12381                final int verificationId = mIntentFilterVerificationToken++;
12382                for (PackageParser.Activity a : pkg.activities) {
12383                    for (ActivityIntentInfo filter : a.intents) {
12384                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12385                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12386                                    "Verification needed for IntentFilter:" + filter.toString());
12387                            mIntentFilterVerifier.addOneIntentFilterVerification(
12388                                    verifierUid, userId, verificationId, filter, packageName);
12389                            count++;
12390                        }
12391                    }
12392                }
12393            }
12394        }
12395
12396        if (count > 0) {
12397            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12398                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12399                    +  " for userId:" + userId);
12400            mIntentFilterVerifier.startVerifications(userId);
12401        } else {
12402            if (DEBUG_DOMAIN_VERIFICATION) {
12403                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12404            }
12405        }
12406    }
12407
12408    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12409        final ComponentName cn  = filter.activity.getComponentName();
12410        final String packageName = cn.getPackageName();
12411
12412        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12413                packageName);
12414        if (ivi == null) {
12415            return true;
12416        }
12417        int status = ivi.getStatus();
12418        switch (status) {
12419            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12420            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12421                return true;
12422
12423            default:
12424                // Nothing to do
12425                return false;
12426        }
12427    }
12428
12429    private static boolean isMultiArch(PackageSetting ps) {
12430        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12431    }
12432
12433    private static boolean isMultiArch(ApplicationInfo info) {
12434        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12435    }
12436
12437    private static boolean isExternal(PackageParser.Package pkg) {
12438        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12439    }
12440
12441    private static boolean isExternal(PackageSetting ps) {
12442        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12443    }
12444
12445    private static boolean isExternal(ApplicationInfo info) {
12446        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12447    }
12448
12449    private static boolean isSystemApp(PackageParser.Package pkg) {
12450        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12451    }
12452
12453    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12454        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12455    }
12456
12457    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12458        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12459    }
12460
12461    private static boolean isSystemApp(PackageSetting ps) {
12462        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12463    }
12464
12465    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12466        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12467    }
12468
12469    private int packageFlagsToInstallFlags(PackageSetting ps) {
12470        int installFlags = 0;
12471        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12472            // This existing package was an external ASEC install when we have
12473            // the external flag without a UUID
12474            installFlags |= PackageManager.INSTALL_EXTERNAL;
12475        }
12476        if (ps.isForwardLocked()) {
12477            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12478        }
12479        return installFlags;
12480    }
12481
12482    private void deleteTempPackageFiles() {
12483        final FilenameFilter filter = new FilenameFilter() {
12484            public boolean accept(File dir, String name) {
12485                return name.startsWith("vmdl") && name.endsWith(".tmp");
12486            }
12487        };
12488        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12489            file.delete();
12490        }
12491    }
12492
12493    @Override
12494    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12495            int flags) {
12496        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12497                flags);
12498    }
12499
12500    @Override
12501    public void deletePackage(final String packageName,
12502            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12503        mContext.enforceCallingOrSelfPermission(
12504                android.Manifest.permission.DELETE_PACKAGES, null);
12505        Preconditions.checkNotNull(packageName);
12506        Preconditions.checkNotNull(observer);
12507        final int uid = Binder.getCallingUid();
12508        if (UserHandle.getUserId(uid) != userId) {
12509            mContext.enforceCallingPermission(
12510                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12511                    "deletePackage for user " + userId);
12512        }
12513        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12514            try {
12515                observer.onPackageDeleted(packageName,
12516                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12517            } catch (RemoteException re) {
12518            }
12519            return;
12520        }
12521
12522        boolean uninstallBlocked = false;
12523        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12524            int[] users = sUserManager.getUserIds();
12525            for (int i = 0; i < users.length; ++i) {
12526                if (getBlockUninstallForUser(packageName, users[i])) {
12527                    uninstallBlocked = true;
12528                    break;
12529                }
12530            }
12531        } else {
12532            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12533        }
12534        if (uninstallBlocked) {
12535            try {
12536                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12537                        null);
12538            } catch (RemoteException re) {
12539            }
12540            return;
12541        }
12542
12543        if (DEBUG_REMOVE) {
12544            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12545        }
12546        // Queue up an async operation since the package deletion may take a little while.
12547        mHandler.post(new Runnable() {
12548            public void run() {
12549                mHandler.removeCallbacks(this);
12550                final int returnCode = deletePackageX(packageName, userId, flags);
12551                if (observer != null) {
12552                    try {
12553                        observer.onPackageDeleted(packageName, returnCode, null);
12554                    } catch (RemoteException e) {
12555                        Log.i(TAG, "Observer no longer exists.");
12556                    } //end catch
12557                } //end if
12558            } //end run
12559        });
12560    }
12561
12562    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12563        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12564                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12565        try {
12566            if (dpm != null) {
12567                if (dpm.isDeviceOwner(packageName)) {
12568                    return true;
12569                }
12570                int[] users;
12571                if (userId == UserHandle.USER_ALL) {
12572                    users = sUserManager.getUserIds();
12573                } else {
12574                    users = new int[]{userId};
12575                }
12576                for (int i = 0; i < users.length; ++i) {
12577                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12578                        return true;
12579                    }
12580                }
12581            }
12582        } catch (RemoteException e) {
12583        }
12584        return false;
12585    }
12586
12587    /**
12588     *  This method is an internal method that could be get invoked either
12589     *  to delete an installed package or to clean up a failed installation.
12590     *  After deleting an installed package, a broadcast is sent to notify any
12591     *  listeners that the package has been installed. For cleaning up a failed
12592     *  installation, the broadcast is not necessary since the package's
12593     *  installation wouldn't have sent the initial broadcast either
12594     *  The key steps in deleting a package are
12595     *  deleting the package information in internal structures like mPackages,
12596     *  deleting the packages base directories through installd
12597     *  updating mSettings to reflect current status
12598     *  persisting settings for later use
12599     *  sending a broadcast if necessary
12600     */
12601    private int deletePackageX(String packageName, int userId, int flags) {
12602        final PackageRemovedInfo info = new PackageRemovedInfo();
12603        final boolean res;
12604
12605        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12606                ? UserHandle.ALL : new UserHandle(userId);
12607
12608        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12609            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12610            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12611        }
12612
12613        boolean removedForAllUsers = false;
12614        boolean systemUpdate = false;
12615
12616        // for the uninstall-updates case and restricted profiles, remember the per-
12617        // userhandle installed state
12618        int[] allUsers;
12619        boolean[] perUserInstalled;
12620        synchronized (mPackages) {
12621            PackageSetting ps = mSettings.mPackages.get(packageName);
12622            allUsers = sUserManager.getUserIds();
12623            perUserInstalled = new boolean[allUsers.length];
12624            for (int i = 0; i < allUsers.length; i++) {
12625                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12626            }
12627        }
12628
12629        synchronized (mInstallLock) {
12630            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12631            res = deletePackageLI(packageName, removeForUser,
12632                    true, allUsers, perUserInstalled,
12633                    flags | REMOVE_CHATTY, info, true);
12634            systemUpdate = info.isRemovedPackageSystemUpdate;
12635            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12636                removedForAllUsers = true;
12637            }
12638            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12639                    + " removedForAllUsers=" + removedForAllUsers);
12640        }
12641
12642        if (res) {
12643            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12644
12645            // If the removed package was a system update, the old system package
12646            // was re-enabled; we need to broadcast this information
12647            if (systemUpdate) {
12648                Bundle extras = new Bundle(1);
12649                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12650                        ? info.removedAppId : info.uid);
12651                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12652
12653                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12654                        extras, null, null, null);
12655                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12656                        extras, null, null, null);
12657                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12658                        null, packageName, null, null);
12659            }
12660        }
12661        // Force a gc here.
12662        Runtime.getRuntime().gc();
12663        // Delete the resources here after sending the broadcast to let
12664        // other processes clean up before deleting resources.
12665        if (info.args != null) {
12666            synchronized (mInstallLock) {
12667                info.args.doPostDeleteLI(true);
12668            }
12669        }
12670
12671        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12672    }
12673
12674    class PackageRemovedInfo {
12675        String removedPackage;
12676        int uid = -1;
12677        int removedAppId = -1;
12678        int[] removedUsers = null;
12679        boolean isRemovedPackageSystemUpdate = false;
12680        // Clean up resources deleted packages.
12681        InstallArgs args = null;
12682
12683        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12684            Bundle extras = new Bundle(1);
12685            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12686            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12687            if (replacing) {
12688                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12689            }
12690            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12691            if (removedPackage != null) {
12692                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12693                        extras, null, null, removedUsers);
12694                if (fullRemove && !replacing) {
12695                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12696                            extras, null, null, removedUsers);
12697                }
12698            }
12699            if (removedAppId >= 0) {
12700                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12701                        removedUsers);
12702            }
12703        }
12704    }
12705
12706    /*
12707     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12708     * flag is not set, the data directory is removed as well.
12709     * make sure this flag is set for partially installed apps. If not its meaningless to
12710     * delete a partially installed application.
12711     */
12712    private void removePackageDataLI(PackageSetting ps,
12713            int[] allUserHandles, boolean[] perUserInstalled,
12714            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12715        String packageName = ps.name;
12716        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12717        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12718        // Retrieve object to delete permissions for shared user later on
12719        final PackageSetting deletedPs;
12720        // reader
12721        synchronized (mPackages) {
12722            deletedPs = mSettings.mPackages.get(packageName);
12723            if (outInfo != null) {
12724                outInfo.removedPackage = packageName;
12725                outInfo.removedUsers = deletedPs != null
12726                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12727                        : null;
12728            }
12729        }
12730        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12731            removeDataDirsLI(ps.volumeUuid, packageName);
12732            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12733        }
12734        // writer
12735        synchronized (mPackages) {
12736            if (deletedPs != null) {
12737                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12738                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12739                    clearDefaultBrowserIfNeeded(packageName);
12740                    if (outInfo != null) {
12741                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12742                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12743                    }
12744                    updatePermissionsLPw(deletedPs.name, null, 0);
12745                    if (deletedPs.sharedUser != null) {
12746                        // Remove permissions associated with package. Since runtime
12747                        // permissions are per user we have to kill the removed package
12748                        // or packages running under the shared user of the removed
12749                        // package if revoking the permissions requested only by the removed
12750                        // package is successful and this causes a change in gids.
12751                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12752                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12753                                    userId);
12754                            if (userIdToKill == UserHandle.USER_ALL
12755                                    || userIdToKill >= UserHandle.USER_OWNER) {
12756                                // If gids changed for this user, kill all affected packages.
12757                                mHandler.post(new Runnable() {
12758                                    @Override
12759                                    public void run() {
12760                                        // This has to happen with no lock held.
12761                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12762                                                KILL_APP_REASON_GIDS_CHANGED);
12763                                    }
12764                                });
12765                                break;
12766                            }
12767                        }
12768                    }
12769                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12770                }
12771                // make sure to preserve per-user disabled state if this removal was just
12772                // a downgrade of a system app to the factory package
12773                if (allUserHandles != null && perUserInstalled != null) {
12774                    if (DEBUG_REMOVE) {
12775                        Slog.d(TAG, "Propagating install state across downgrade");
12776                    }
12777                    for (int i = 0; i < allUserHandles.length; i++) {
12778                        if (DEBUG_REMOVE) {
12779                            Slog.d(TAG, "    user " + allUserHandles[i]
12780                                    + " => " + perUserInstalled[i]);
12781                        }
12782                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12783                    }
12784                }
12785            }
12786            // can downgrade to reader
12787            if (writeSettings) {
12788                // Save settings now
12789                mSettings.writeLPr();
12790            }
12791        }
12792        if (outInfo != null) {
12793            // A user ID was deleted here. Go through all users and remove it
12794            // from KeyStore.
12795            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12796        }
12797    }
12798
12799    static boolean locationIsPrivileged(File path) {
12800        try {
12801            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12802                    .getCanonicalPath();
12803            return path.getCanonicalPath().startsWith(privilegedAppDir);
12804        } catch (IOException e) {
12805            Slog.e(TAG, "Unable to access code path " + path);
12806        }
12807        return false;
12808    }
12809
12810    /*
12811     * Tries to delete system package.
12812     */
12813    private boolean deleteSystemPackageLI(PackageSetting newPs,
12814            int[] allUserHandles, boolean[] perUserInstalled,
12815            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12816        final boolean applyUserRestrictions
12817                = (allUserHandles != null) && (perUserInstalled != null);
12818        PackageSetting disabledPs = null;
12819        // Confirm if the system package has been updated
12820        // An updated system app can be deleted. This will also have to restore
12821        // the system pkg from system partition
12822        // reader
12823        synchronized (mPackages) {
12824            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12825        }
12826        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12827                + " disabledPs=" + disabledPs);
12828        if (disabledPs == null) {
12829            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12830            return false;
12831        } else if (DEBUG_REMOVE) {
12832            Slog.d(TAG, "Deleting system pkg from data partition");
12833        }
12834        if (DEBUG_REMOVE) {
12835            if (applyUserRestrictions) {
12836                Slog.d(TAG, "Remembering install states:");
12837                for (int i = 0; i < allUserHandles.length; i++) {
12838                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12839                }
12840            }
12841        }
12842        // Delete the updated package
12843        outInfo.isRemovedPackageSystemUpdate = true;
12844        if (disabledPs.versionCode < newPs.versionCode) {
12845            // Delete data for downgrades
12846            flags &= ~PackageManager.DELETE_KEEP_DATA;
12847        } else {
12848            // Preserve data by setting flag
12849            flags |= PackageManager.DELETE_KEEP_DATA;
12850        }
12851        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12852                allUserHandles, perUserInstalled, outInfo, writeSettings);
12853        if (!ret) {
12854            return false;
12855        }
12856        // writer
12857        synchronized (mPackages) {
12858            // Reinstate the old system package
12859            mSettings.enableSystemPackageLPw(newPs.name);
12860            // Remove any native libraries from the upgraded package.
12861            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12862        }
12863        // Install the system package
12864        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12865        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12866        if (locationIsPrivileged(disabledPs.codePath)) {
12867            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12868        }
12869
12870        final PackageParser.Package newPkg;
12871        try {
12872            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12873        } catch (PackageManagerException e) {
12874            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12875            return false;
12876        }
12877
12878        // writer
12879        synchronized (mPackages) {
12880            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12881
12882            // Propagate the permissions state as we do want to drop on the floor
12883            // runtime permissions. The update permissions method below will take
12884            // care of removing obsolete permissions and grant install permissions.
12885            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12886            updatePermissionsLPw(newPkg.packageName, newPkg,
12887                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12888
12889            if (applyUserRestrictions) {
12890                if (DEBUG_REMOVE) {
12891                    Slog.d(TAG, "Propagating install state across reinstall");
12892                }
12893                for (int i = 0; i < allUserHandles.length; i++) {
12894                    if (DEBUG_REMOVE) {
12895                        Slog.d(TAG, "    user " + allUserHandles[i]
12896                                + " => " + perUserInstalled[i]);
12897                    }
12898                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12899                }
12900                // Regardless of writeSettings we need to ensure that this restriction
12901                // state propagation is persisted
12902                mSettings.writeAllUsersPackageRestrictionsLPr();
12903            }
12904            // can downgrade to reader here
12905            if (writeSettings) {
12906                mSettings.writeLPr();
12907            }
12908        }
12909        return true;
12910    }
12911
12912    private boolean deleteInstalledPackageLI(PackageSetting ps,
12913            boolean deleteCodeAndResources, int flags,
12914            int[] allUserHandles, boolean[] perUserInstalled,
12915            PackageRemovedInfo outInfo, boolean writeSettings) {
12916        if (outInfo != null) {
12917            outInfo.uid = ps.appId;
12918        }
12919
12920        // Delete package data from internal structures and also remove data if flag is set
12921        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12922
12923        // Delete application code and resources
12924        if (deleteCodeAndResources && (outInfo != null)) {
12925            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12926                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12927            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12928        }
12929        return true;
12930    }
12931
12932    @Override
12933    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12934            int userId) {
12935        mContext.enforceCallingOrSelfPermission(
12936                android.Manifest.permission.DELETE_PACKAGES, null);
12937        synchronized (mPackages) {
12938            PackageSetting ps = mSettings.mPackages.get(packageName);
12939            if (ps == null) {
12940                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12941                return false;
12942            }
12943            if (!ps.getInstalled(userId)) {
12944                // Can't block uninstall for an app that is not installed or enabled.
12945                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12946                return false;
12947            }
12948            ps.setBlockUninstall(blockUninstall, userId);
12949            mSettings.writePackageRestrictionsLPr(userId);
12950        }
12951        return true;
12952    }
12953
12954    @Override
12955    public boolean getBlockUninstallForUser(String packageName, int userId) {
12956        synchronized (mPackages) {
12957            PackageSetting ps = mSettings.mPackages.get(packageName);
12958            if (ps == null) {
12959                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12960                return false;
12961            }
12962            return ps.getBlockUninstall(userId);
12963        }
12964    }
12965
12966    /*
12967     * This method handles package deletion in general
12968     */
12969    private boolean deletePackageLI(String packageName, UserHandle user,
12970            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12971            int flags, PackageRemovedInfo outInfo,
12972            boolean writeSettings) {
12973        if (packageName == null) {
12974            Slog.w(TAG, "Attempt to delete null packageName.");
12975            return false;
12976        }
12977        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12978        PackageSetting ps;
12979        boolean dataOnly = false;
12980        int removeUser = -1;
12981        int appId = -1;
12982        synchronized (mPackages) {
12983            ps = mSettings.mPackages.get(packageName);
12984            if (ps == null) {
12985                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12986                return false;
12987            }
12988            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12989                    && user.getIdentifier() != UserHandle.USER_ALL) {
12990                // The caller is asking that the package only be deleted for a single
12991                // user.  To do this, we just mark its uninstalled state and delete
12992                // its data.  If this is a system app, we only allow this to happen if
12993                // they have set the special DELETE_SYSTEM_APP which requests different
12994                // semantics than normal for uninstalling system apps.
12995                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12996                ps.setUserState(user.getIdentifier(),
12997                        COMPONENT_ENABLED_STATE_DEFAULT,
12998                        false, //installed
12999                        true,  //stopped
13000                        true,  //notLaunched
13001                        false, //hidden
13002                        null, null, null,
13003                        false, // blockUninstall
13004                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13005                if (!isSystemApp(ps)) {
13006                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13007                        // Other user still have this package installed, so all
13008                        // we need to do is clear this user's data and save that
13009                        // it is uninstalled.
13010                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13011                        removeUser = user.getIdentifier();
13012                        appId = ps.appId;
13013                        scheduleWritePackageRestrictionsLocked(removeUser);
13014                    } else {
13015                        // We need to set it back to 'installed' so the uninstall
13016                        // broadcasts will be sent correctly.
13017                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13018                        ps.setInstalled(true, user.getIdentifier());
13019                    }
13020                } else {
13021                    // This is a system app, so we assume that the
13022                    // other users still have this package installed, so all
13023                    // we need to do is clear this user's data and save that
13024                    // it is uninstalled.
13025                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13026                    removeUser = user.getIdentifier();
13027                    appId = ps.appId;
13028                    scheduleWritePackageRestrictionsLocked(removeUser);
13029                }
13030            }
13031        }
13032
13033        if (removeUser >= 0) {
13034            // From above, we determined that we are deleting this only
13035            // for a single user.  Continue the work here.
13036            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13037            if (outInfo != null) {
13038                outInfo.removedPackage = packageName;
13039                outInfo.removedAppId = appId;
13040                outInfo.removedUsers = new int[] {removeUser};
13041            }
13042            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13043            removeKeystoreDataIfNeeded(removeUser, appId);
13044            schedulePackageCleaning(packageName, removeUser, false);
13045            synchronized (mPackages) {
13046                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13047                    scheduleWritePackageRestrictionsLocked(removeUser);
13048                }
13049                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13050            }
13051            return true;
13052        }
13053
13054        if (dataOnly) {
13055            // Delete application data first
13056            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13057            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13058            return true;
13059        }
13060
13061        boolean ret = false;
13062        if (isSystemApp(ps)) {
13063            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13064            // When an updated system application is deleted we delete the existing resources as well and
13065            // fall back to existing code in system partition
13066            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13067                    flags, outInfo, writeSettings);
13068        } else {
13069            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13070            // Kill application pre-emptively especially for apps on sd.
13071            killApplication(packageName, ps.appId, "uninstall pkg");
13072            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13073                    allUserHandles, perUserInstalled,
13074                    outInfo, writeSettings);
13075        }
13076
13077        return ret;
13078    }
13079
13080    private final class ClearStorageConnection implements ServiceConnection {
13081        IMediaContainerService mContainerService;
13082
13083        @Override
13084        public void onServiceConnected(ComponentName name, IBinder service) {
13085            synchronized (this) {
13086                mContainerService = IMediaContainerService.Stub.asInterface(service);
13087                notifyAll();
13088            }
13089        }
13090
13091        @Override
13092        public void onServiceDisconnected(ComponentName name) {
13093        }
13094    }
13095
13096    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13097        final boolean mounted;
13098        if (Environment.isExternalStorageEmulated()) {
13099            mounted = true;
13100        } else {
13101            final String status = Environment.getExternalStorageState();
13102
13103            mounted = status.equals(Environment.MEDIA_MOUNTED)
13104                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13105        }
13106
13107        if (!mounted) {
13108            return;
13109        }
13110
13111        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13112        int[] users;
13113        if (userId == UserHandle.USER_ALL) {
13114            users = sUserManager.getUserIds();
13115        } else {
13116            users = new int[] { userId };
13117        }
13118        final ClearStorageConnection conn = new ClearStorageConnection();
13119        if (mContext.bindServiceAsUser(
13120                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13121            try {
13122                for (int curUser : users) {
13123                    long timeout = SystemClock.uptimeMillis() + 5000;
13124                    synchronized (conn) {
13125                        long now = SystemClock.uptimeMillis();
13126                        while (conn.mContainerService == null && now < timeout) {
13127                            try {
13128                                conn.wait(timeout - now);
13129                            } catch (InterruptedException e) {
13130                            }
13131                        }
13132                    }
13133                    if (conn.mContainerService == null) {
13134                        return;
13135                    }
13136
13137                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13138                    clearDirectory(conn.mContainerService,
13139                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13140                    if (allData) {
13141                        clearDirectory(conn.mContainerService,
13142                                userEnv.buildExternalStorageAppDataDirs(packageName));
13143                        clearDirectory(conn.mContainerService,
13144                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13145                    }
13146                }
13147            } finally {
13148                mContext.unbindService(conn);
13149            }
13150        }
13151    }
13152
13153    @Override
13154    public void clearApplicationUserData(final String packageName,
13155            final IPackageDataObserver observer, final int userId) {
13156        mContext.enforceCallingOrSelfPermission(
13157                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13158        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13159        // Queue up an async operation since the package deletion may take a little while.
13160        mHandler.post(new Runnable() {
13161            public void run() {
13162                mHandler.removeCallbacks(this);
13163                final boolean succeeded;
13164                synchronized (mInstallLock) {
13165                    succeeded = clearApplicationUserDataLI(packageName, userId);
13166                }
13167                clearExternalStorageDataSync(packageName, userId, true);
13168                if (succeeded) {
13169                    // invoke DeviceStorageMonitor's update method to clear any notifications
13170                    DeviceStorageMonitorInternal
13171                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13172                    if (dsm != null) {
13173                        dsm.checkMemory();
13174                    }
13175                }
13176                if(observer != null) {
13177                    try {
13178                        observer.onRemoveCompleted(packageName, succeeded);
13179                    } catch (RemoteException e) {
13180                        Log.i(TAG, "Observer no longer exists.");
13181                    }
13182                } //end if observer
13183            } //end run
13184        });
13185    }
13186
13187    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13188        if (packageName == null) {
13189            Slog.w(TAG, "Attempt to delete null packageName.");
13190            return false;
13191        }
13192
13193        // Try finding details about the requested package
13194        PackageParser.Package pkg;
13195        synchronized (mPackages) {
13196            pkg = mPackages.get(packageName);
13197            if (pkg == null) {
13198                final PackageSetting ps = mSettings.mPackages.get(packageName);
13199                if (ps != null) {
13200                    pkg = ps.pkg;
13201                }
13202            }
13203
13204            if (pkg == null) {
13205                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13206                return false;
13207            }
13208
13209            PackageSetting ps = (PackageSetting) pkg.mExtras;
13210            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13211        }
13212
13213        // Always delete data directories for package, even if we found no other
13214        // record of app. This helps users recover from UID mismatches without
13215        // resorting to a full data wipe.
13216        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13217        if (retCode < 0) {
13218            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13219            return false;
13220        }
13221
13222        final int appId = pkg.applicationInfo.uid;
13223        removeKeystoreDataIfNeeded(userId, appId);
13224
13225        // Create a native library symlink only if we have native libraries
13226        // and if the native libraries are 32 bit libraries. We do not provide
13227        // this symlink for 64 bit libraries.
13228        if (pkg.applicationInfo.primaryCpuAbi != null &&
13229                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13230            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13231            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13232                    nativeLibPath, userId) < 0) {
13233                Slog.w(TAG, "Failed linking native library dir");
13234                return false;
13235            }
13236        }
13237
13238        return true;
13239    }
13240
13241    /**
13242     * Reverts user permission state changes (permissions and flags).
13243     *
13244     * @param ps The package for which to reset.
13245     * @param userId The device user for which to do a reset.
13246     */
13247    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13248            final PackageSetting ps, final int userId) {
13249        if (ps.pkg == null) {
13250            return;
13251        }
13252
13253        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13254                | FLAG_PERMISSION_USER_FIXED
13255                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13256
13257        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13258                | FLAG_PERMISSION_POLICY_FIXED;
13259
13260        boolean writeInstallPermissions = false;
13261        boolean writeRuntimePermissions = false;
13262
13263        final int permissionCount = ps.pkg.requestedPermissions.size();
13264        for (int i = 0; i < permissionCount; i++) {
13265            String permission = ps.pkg.requestedPermissions.get(i);
13266
13267            BasePermission bp = mSettings.mPermissions.get(permission);
13268            if (bp == null) {
13269                continue;
13270            }
13271
13272            // If shared user we just reset the state to which only this app contributed.
13273            if (ps.sharedUser != null) {
13274                boolean used = false;
13275                final int packageCount = ps.sharedUser.packages.size();
13276                for (int j = 0; j < packageCount; j++) {
13277                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13278                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13279                            && pkg.pkg.requestedPermissions.contains(permission)) {
13280                        used = true;
13281                        break;
13282                    }
13283                }
13284                if (used) {
13285                    continue;
13286                }
13287            }
13288
13289            PermissionsState permissionsState = ps.getPermissionsState();
13290
13291            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13292
13293            // Always clear the user settable flags.
13294            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13295                    bp.name) != null;
13296            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13297                if (hasInstallState) {
13298                    writeInstallPermissions = true;
13299                } else {
13300                    writeRuntimePermissions = true;
13301                }
13302            }
13303
13304            // Below is only runtime permission handling.
13305            if (!bp.isRuntime()) {
13306                continue;
13307            }
13308
13309            // Never clobber system or policy.
13310            if ((oldFlags & policyOrSystemFlags) != 0) {
13311                continue;
13312            }
13313
13314            // If this permission was granted by default, make sure it is.
13315            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13316                if (permissionsState.grantRuntimePermission(bp, userId)
13317                        != PERMISSION_OPERATION_FAILURE) {
13318                    writeRuntimePermissions = true;
13319                }
13320            } else {
13321                // Otherwise, reset the permission.
13322                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13323                switch (revokeResult) {
13324                    case PERMISSION_OPERATION_SUCCESS: {
13325                        writeRuntimePermissions = true;
13326                    } break;
13327
13328                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13329                        writeRuntimePermissions = true;
13330                        // If gids changed for this user, kill all affected packages.
13331                        mHandler.post(new Runnable() {
13332                            @Override
13333                            public void run() {
13334                                // This has to happen with no lock held.
13335                                killSettingPackagesForUser(ps, userId,
13336                                        KILL_APP_REASON_GIDS_CHANGED);
13337                            }
13338                        });
13339                    } break;
13340                }
13341            }
13342        }
13343
13344        // Synchronously write as we are taking permissions away.
13345        if (writeRuntimePermissions) {
13346            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13347        }
13348
13349        // Synchronously write as we are taking permissions away.
13350        if (writeInstallPermissions) {
13351            mSettings.writeLPr();
13352        }
13353    }
13354
13355    /**
13356     * Remove entries from the keystore daemon. Will only remove it if the
13357     * {@code appId} is valid.
13358     */
13359    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13360        if (appId < 0) {
13361            return;
13362        }
13363
13364        final KeyStore keyStore = KeyStore.getInstance();
13365        if (keyStore != null) {
13366            if (userId == UserHandle.USER_ALL) {
13367                for (final int individual : sUserManager.getUserIds()) {
13368                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13369                }
13370            } else {
13371                keyStore.clearUid(UserHandle.getUid(userId, appId));
13372            }
13373        } else {
13374            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13375        }
13376    }
13377
13378    @Override
13379    public void deleteApplicationCacheFiles(final String packageName,
13380            final IPackageDataObserver observer) {
13381        mContext.enforceCallingOrSelfPermission(
13382                android.Manifest.permission.DELETE_CACHE_FILES, null);
13383        // Queue up an async operation since the package deletion may take a little while.
13384        final int userId = UserHandle.getCallingUserId();
13385        mHandler.post(new Runnable() {
13386            public void run() {
13387                mHandler.removeCallbacks(this);
13388                final boolean succeded;
13389                synchronized (mInstallLock) {
13390                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13391                }
13392                clearExternalStorageDataSync(packageName, userId, false);
13393                if (observer != null) {
13394                    try {
13395                        observer.onRemoveCompleted(packageName, succeded);
13396                    } catch (RemoteException e) {
13397                        Log.i(TAG, "Observer no longer exists.");
13398                    }
13399                } //end if observer
13400            } //end run
13401        });
13402    }
13403
13404    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13405        if (packageName == null) {
13406            Slog.w(TAG, "Attempt to delete null packageName.");
13407            return false;
13408        }
13409        PackageParser.Package p;
13410        synchronized (mPackages) {
13411            p = mPackages.get(packageName);
13412        }
13413        if (p == null) {
13414            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13415            return false;
13416        }
13417        final ApplicationInfo applicationInfo = p.applicationInfo;
13418        if (applicationInfo == null) {
13419            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13420            return false;
13421        }
13422        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13423        if (retCode < 0) {
13424            Slog.w(TAG, "Couldn't remove cache files for package: "
13425                       + packageName + " u" + userId);
13426            return false;
13427        }
13428        return true;
13429    }
13430
13431    @Override
13432    public void getPackageSizeInfo(final String packageName, int userHandle,
13433            final IPackageStatsObserver observer) {
13434        mContext.enforceCallingOrSelfPermission(
13435                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13436        if (packageName == null) {
13437            throw new IllegalArgumentException("Attempt to get size of null packageName");
13438        }
13439
13440        PackageStats stats = new PackageStats(packageName, userHandle);
13441
13442        /*
13443         * Queue up an async operation since the package measurement may take a
13444         * little while.
13445         */
13446        Message msg = mHandler.obtainMessage(INIT_COPY);
13447        msg.obj = new MeasureParams(stats, observer);
13448        mHandler.sendMessage(msg);
13449    }
13450
13451    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13452            PackageStats pStats) {
13453        if (packageName == null) {
13454            Slog.w(TAG, "Attempt to get size of null packageName.");
13455            return false;
13456        }
13457        PackageParser.Package p;
13458        boolean dataOnly = false;
13459        String libDirRoot = null;
13460        String asecPath = null;
13461        PackageSetting ps = null;
13462        synchronized (mPackages) {
13463            p = mPackages.get(packageName);
13464            ps = mSettings.mPackages.get(packageName);
13465            if(p == null) {
13466                dataOnly = true;
13467                if((ps == null) || (ps.pkg == null)) {
13468                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13469                    return false;
13470                }
13471                p = ps.pkg;
13472            }
13473            if (ps != null) {
13474                libDirRoot = ps.legacyNativeLibraryPathString;
13475            }
13476            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13477                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13478                if (secureContainerId != null) {
13479                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13480                }
13481            }
13482        }
13483        String publicSrcDir = null;
13484        if(!dataOnly) {
13485            final ApplicationInfo applicationInfo = p.applicationInfo;
13486            if (applicationInfo == null) {
13487                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13488                return false;
13489            }
13490            if (p.isForwardLocked()) {
13491                publicSrcDir = applicationInfo.getBaseResourcePath();
13492            }
13493        }
13494        // TODO: extend to measure size of split APKs
13495        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13496        // not just the first level.
13497        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13498        // just the primary.
13499        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13500        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13501                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13502        if (res < 0) {
13503            return false;
13504        }
13505
13506        // Fix-up for forward-locked applications in ASEC containers.
13507        if (!isExternal(p)) {
13508            pStats.codeSize += pStats.externalCodeSize;
13509            pStats.externalCodeSize = 0L;
13510        }
13511
13512        return true;
13513    }
13514
13515
13516    @Override
13517    public void addPackageToPreferred(String packageName) {
13518        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13519    }
13520
13521    @Override
13522    public void removePackageFromPreferred(String packageName) {
13523        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13524    }
13525
13526    @Override
13527    public List<PackageInfo> getPreferredPackages(int flags) {
13528        return new ArrayList<PackageInfo>();
13529    }
13530
13531    private int getUidTargetSdkVersionLockedLPr(int uid) {
13532        Object obj = mSettings.getUserIdLPr(uid);
13533        if (obj instanceof SharedUserSetting) {
13534            final SharedUserSetting sus = (SharedUserSetting) obj;
13535            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13536            final Iterator<PackageSetting> it = sus.packages.iterator();
13537            while (it.hasNext()) {
13538                final PackageSetting ps = it.next();
13539                if (ps.pkg != null) {
13540                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13541                    if (v < vers) vers = v;
13542                }
13543            }
13544            return vers;
13545        } else if (obj instanceof PackageSetting) {
13546            final PackageSetting ps = (PackageSetting) obj;
13547            if (ps.pkg != null) {
13548                return ps.pkg.applicationInfo.targetSdkVersion;
13549            }
13550        }
13551        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13552    }
13553
13554    @Override
13555    public void addPreferredActivity(IntentFilter filter, int match,
13556            ComponentName[] set, ComponentName activity, int userId) {
13557        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13558                "Adding preferred");
13559    }
13560
13561    private void addPreferredActivityInternal(IntentFilter filter, int match,
13562            ComponentName[] set, ComponentName activity, boolean always, int userId,
13563            String opname) {
13564        // writer
13565        int callingUid = Binder.getCallingUid();
13566        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13567        if (filter.countActions() == 0) {
13568            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13569            return;
13570        }
13571        synchronized (mPackages) {
13572            if (mContext.checkCallingOrSelfPermission(
13573                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13574                    != PackageManager.PERMISSION_GRANTED) {
13575                if (getUidTargetSdkVersionLockedLPr(callingUid)
13576                        < Build.VERSION_CODES.FROYO) {
13577                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13578                            + callingUid);
13579                    return;
13580                }
13581                mContext.enforceCallingOrSelfPermission(
13582                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13583            }
13584
13585            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13586            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13587                    + userId + ":");
13588            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13589            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13590            scheduleWritePackageRestrictionsLocked(userId);
13591        }
13592    }
13593
13594    @Override
13595    public void replacePreferredActivity(IntentFilter filter, int match,
13596            ComponentName[] set, ComponentName activity, int userId) {
13597        if (filter.countActions() != 1) {
13598            throw new IllegalArgumentException(
13599                    "replacePreferredActivity expects filter to have only 1 action.");
13600        }
13601        if (filter.countDataAuthorities() != 0
13602                || filter.countDataPaths() != 0
13603                || filter.countDataSchemes() > 1
13604                || filter.countDataTypes() != 0) {
13605            throw new IllegalArgumentException(
13606                    "replacePreferredActivity expects filter to have no data authorities, " +
13607                    "paths, or types; and at most one scheme.");
13608        }
13609
13610        final int callingUid = Binder.getCallingUid();
13611        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13612        synchronized (mPackages) {
13613            if (mContext.checkCallingOrSelfPermission(
13614                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13615                    != PackageManager.PERMISSION_GRANTED) {
13616                if (getUidTargetSdkVersionLockedLPr(callingUid)
13617                        < Build.VERSION_CODES.FROYO) {
13618                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13619                            + Binder.getCallingUid());
13620                    return;
13621                }
13622                mContext.enforceCallingOrSelfPermission(
13623                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13624            }
13625
13626            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13627            if (pir != null) {
13628                // Get all of the existing entries that exactly match this filter.
13629                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13630                if (existing != null && existing.size() == 1) {
13631                    PreferredActivity cur = existing.get(0);
13632                    if (DEBUG_PREFERRED) {
13633                        Slog.i(TAG, "Checking replace of preferred:");
13634                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13635                        if (!cur.mPref.mAlways) {
13636                            Slog.i(TAG, "  -- CUR; not mAlways!");
13637                        } else {
13638                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13639                            Slog.i(TAG, "  -- CUR: mSet="
13640                                    + Arrays.toString(cur.mPref.mSetComponents));
13641                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13642                            Slog.i(TAG, "  -- NEW: mMatch="
13643                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13644                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13645                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13646                        }
13647                    }
13648                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13649                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13650                            && cur.mPref.sameSet(set)) {
13651                        // Setting the preferred activity to what it happens to be already
13652                        if (DEBUG_PREFERRED) {
13653                            Slog.i(TAG, "Replacing with same preferred activity "
13654                                    + cur.mPref.mShortComponent + " for user "
13655                                    + userId + ":");
13656                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13657                        }
13658                        return;
13659                    }
13660                }
13661
13662                if (existing != null) {
13663                    if (DEBUG_PREFERRED) {
13664                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13665                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13666                    }
13667                    for (int i = 0; i < existing.size(); i++) {
13668                        PreferredActivity pa = existing.get(i);
13669                        if (DEBUG_PREFERRED) {
13670                            Slog.i(TAG, "Removing existing preferred activity "
13671                                    + pa.mPref.mComponent + ":");
13672                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13673                        }
13674                        pir.removeFilter(pa);
13675                    }
13676                }
13677            }
13678            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13679                    "Replacing preferred");
13680        }
13681    }
13682
13683    @Override
13684    public void clearPackagePreferredActivities(String packageName) {
13685        final int uid = Binder.getCallingUid();
13686        // writer
13687        synchronized (mPackages) {
13688            PackageParser.Package pkg = mPackages.get(packageName);
13689            if (pkg == null || pkg.applicationInfo.uid != uid) {
13690                if (mContext.checkCallingOrSelfPermission(
13691                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13692                        != PackageManager.PERMISSION_GRANTED) {
13693                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13694                            < Build.VERSION_CODES.FROYO) {
13695                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13696                                + Binder.getCallingUid());
13697                        return;
13698                    }
13699                    mContext.enforceCallingOrSelfPermission(
13700                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13701                }
13702            }
13703
13704            int user = UserHandle.getCallingUserId();
13705            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13706                scheduleWritePackageRestrictionsLocked(user);
13707            }
13708        }
13709    }
13710
13711    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13712    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13713        ArrayList<PreferredActivity> removed = null;
13714        boolean changed = false;
13715        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13716            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13717            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13718            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13719                continue;
13720            }
13721            Iterator<PreferredActivity> it = pir.filterIterator();
13722            while (it.hasNext()) {
13723                PreferredActivity pa = it.next();
13724                // Mark entry for removal only if it matches the package name
13725                // and the entry is of type "always".
13726                if (packageName == null ||
13727                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13728                                && pa.mPref.mAlways)) {
13729                    if (removed == null) {
13730                        removed = new ArrayList<PreferredActivity>();
13731                    }
13732                    removed.add(pa);
13733                }
13734            }
13735            if (removed != null) {
13736                for (int j=0; j<removed.size(); j++) {
13737                    PreferredActivity pa = removed.get(j);
13738                    pir.removeFilter(pa);
13739                }
13740                changed = true;
13741            }
13742        }
13743        return changed;
13744    }
13745
13746    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13747    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13748        if (userId == UserHandle.USER_ALL) {
13749            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13750                    sUserManager.getUserIds())) {
13751                for (int oneUserId : sUserManager.getUserIds()) {
13752                    scheduleWritePackageRestrictionsLocked(oneUserId);
13753                }
13754            }
13755        } else {
13756            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13757                scheduleWritePackageRestrictionsLocked(userId);
13758            }
13759        }
13760    }
13761
13762
13763    void clearDefaultBrowserIfNeeded(String packageName) {
13764        for (int oneUserId : sUserManager.getUserIds()) {
13765            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13766            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13767            if (packageName.equals(defaultBrowserPackageName)) {
13768                setDefaultBrowserPackageName(null, oneUserId);
13769            }
13770        }
13771    }
13772
13773    @Override
13774    public void resetPreferredActivities(int userId) {
13775        mContext.enforceCallingOrSelfPermission(
13776                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13777        // writer
13778        synchronized (mPackages) {
13779            clearPackagePreferredActivitiesLPw(null, userId);
13780            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13781            applyFactoryDefaultBrowserLPw(userId);
13782            primeDomainVerificationsLPw(userId);
13783
13784            scheduleWritePackageRestrictionsLocked(userId);
13785        }
13786    }
13787
13788    @Override
13789    public int getPreferredActivities(List<IntentFilter> outFilters,
13790            List<ComponentName> outActivities, String packageName) {
13791
13792        int num = 0;
13793        final int userId = UserHandle.getCallingUserId();
13794        // reader
13795        synchronized (mPackages) {
13796            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13797            if (pir != null) {
13798                final Iterator<PreferredActivity> it = pir.filterIterator();
13799                while (it.hasNext()) {
13800                    final PreferredActivity pa = it.next();
13801                    if (packageName == null
13802                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13803                                    && pa.mPref.mAlways)) {
13804                        if (outFilters != null) {
13805                            outFilters.add(new IntentFilter(pa));
13806                        }
13807                        if (outActivities != null) {
13808                            outActivities.add(pa.mPref.mComponent);
13809                        }
13810                    }
13811                }
13812            }
13813        }
13814
13815        return num;
13816    }
13817
13818    @Override
13819    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13820            int userId) {
13821        int callingUid = Binder.getCallingUid();
13822        if (callingUid != Process.SYSTEM_UID) {
13823            throw new SecurityException(
13824                    "addPersistentPreferredActivity can only be run by the system");
13825        }
13826        if (filter.countActions() == 0) {
13827            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13828            return;
13829        }
13830        synchronized (mPackages) {
13831            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13832                    " :");
13833            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13834            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13835                    new PersistentPreferredActivity(filter, activity));
13836            scheduleWritePackageRestrictionsLocked(userId);
13837        }
13838    }
13839
13840    @Override
13841    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13842        int callingUid = Binder.getCallingUid();
13843        if (callingUid != Process.SYSTEM_UID) {
13844            throw new SecurityException(
13845                    "clearPackagePersistentPreferredActivities can only be run by the system");
13846        }
13847        ArrayList<PersistentPreferredActivity> removed = null;
13848        boolean changed = false;
13849        synchronized (mPackages) {
13850            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13851                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13852                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13853                        .valueAt(i);
13854                if (userId != thisUserId) {
13855                    continue;
13856                }
13857                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13858                while (it.hasNext()) {
13859                    PersistentPreferredActivity ppa = it.next();
13860                    // Mark entry for removal only if it matches the package name.
13861                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13862                        if (removed == null) {
13863                            removed = new ArrayList<PersistentPreferredActivity>();
13864                        }
13865                        removed.add(ppa);
13866                    }
13867                }
13868                if (removed != null) {
13869                    for (int j=0; j<removed.size(); j++) {
13870                        PersistentPreferredActivity ppa = removed.get(j);
13871                        ppir.removeFilter(ppa);
13872                    }
13873                    changed = true;
13874                }
13875            }
13876
13877            if (changed) {
13878                scheduleWritePackageRestrictionsLocked(userId);
13879            }
13880        }
13881    }
13882
13883    /**
13884     * Common machinery for picking apart a restored XML blob and passing
13885     * it to a caller-supplied functor to be applied to the running system.
13886     */
13887    private void restoreFromXml(XmlPullParser parser, int userId,
13888            String expectedStartTag, BlobXmlRestorer functor)
13889            throws IOException, XmlPullParserException {
13890        int type;
13891        while ((type = parser.next()) != XmlPullParser.START_TAG
13892                && type != XmlPullParser.END_DOCUMENT) {
13893        }
13894        if (type != XmlPullParser.START_TAG) {
13895            // oops didn't find a start tag?!
13896            if (DEBUG_BACKUP) {
13897                Slog.e(TAG, "Didn't find start tag during restore");
13898            }
13899            return;
13900        }
13901
13902        // this is supposed to be TAG_PREFERRED_BACKUP
13903        if (!expectedStartTag.equals(parser.getName())) {
13904            if (DEBUG_BACKUP) {
13905                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13906            }
13907            return;
13908        }
13909
13910        // skip interfering stuff, then we're aligned with the backing implementation
13911        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13912        functor.apply(parser, userId);
13913    }
13914
13915    private interface BlobXmlRestorer {
13916        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13917    }
13918
13919    /**
13920     * Non-Binder method, support for the backup/restore mechanism: write the
13921     * full set of preferred activities in its canonical XML format.  Returns the
13922     * XML output as a byte array, or null if there is none.
13923     */
13924    @Override
13925    public byte[] getPreferredActivityBackup(int userId) {
13926        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13927            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13928        }
13929
13930        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13931        try {
13932            final XmlSerializer serializer = new FastXmlSerializer();
13933            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13934            serializer.startDocument(null, true);
13935            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13936
13937            synchronized (mPackages) {
13938                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13939            }
13940
13941            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13942            serializer.endDocument();
13943            serializer.flush();
13944        } catch (Exception e) {
13945            if (DEBUG_BACKUP) {
13946                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13947            }
13948            return null;
13949        }
13950
13951        return dataStream.toByteArray();
13952    }
13953
13954    @Override
13955    public void restorePreferredActivities(byte[] backup, int userId) {
13956        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13957            throw new SecurityException("Only the system may call restorePreferredActivities()");
13958        }
13959
13960        try {
13961            final XmlPullParser parser = Xml.newPullParser();
13962            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13963            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13964                    new BlobXmlRestorer() {
13965                        @Override
13966                        public void apply(XmlPullParser parser, int userId)
13967                                throws XmlPullParserException, IOException {
13968                            synchronized (mPackages) {
13969                                mSettings.readPreferredActivitiesLPw(parser, userId);
13970                            }
13971                        }
13972                    } );
13973        } catch (Exception e) {
13974            if (DEBUG_BACKUP) {
13975                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13976            }
13977        }
13978    }
13979
13980    /**
13981     * Non-Binder method, support for the backup/restore mechanism: write the
13982     * default browser (etc) settings in its canonical XML format.  Returns the default
13983     * browser XML representation as a byte array, or null if there is none.
13984     */
13985    @Override
13986    public byte[] getDefaultAppsBackup(int userId) {
13987        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13988            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13989        }
13990
13991        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13992        try {
13993            final XmlSerializer serializer = new FastXmlSerializer();
13994            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13995            serializer.startDocument(null, true);
13996            serializer.startTag(null, TAG_DEFAULT_APPS);
13997
13998            synchronized (mPackages) {
13999                mSettings.writeDefaultAppsLPr(serializer, userId);
14000            }
14001
14002            serializer.endTag(null, TAG_DEFAULT_APPS);
14003            serializer.endDocument();
14004            serializer.flush();
14005        } catch (Exception e) {
14006            if (DEBUG_BACKUP) {
14007                Slog.e(TAG, "Unable to write default apps for backup", e);
14008            }
14009            return null;
14010        }
14011
14012        return dataStream.toByteArray();
14013    }
14014
14015    @Override
14016    public void restoreDefaultApps(byte[] backup, int userId) {
14017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14018            throw new SecurityException("Only the system may call restoreDefaultApps()");
14019        }
14020
14021        try {
14022            final XmlPullParser parser = Xml.newPullParser();
14023            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14024            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14025                    new BlobXmlRestorer() {
14026                        @Override
14027                        public void apply(XmlPullParser parser, int userId)
14028                                throws XmlPullParserException, IOException {
14029                            synchronized (mPackages) {
14030                                mSettings.readDefaultAppsLPw(parser, userId);
14031                            }
14032                        }
14033                    } );
14034        } catch (Exception e) {
14035            if (DEBUG_BACKUP) {
14036                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14037            }
14038        }
14039    }
14040
14041    @Override
14042    public byte[] getIntentFilterVerificationBackup(int userId) {
14043        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14044            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14045        }
14046
14047        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14048        try {
14049            final XmlSerializer serializer = new FastXmlSerializer();
14050            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14051            serializer.startDocument(null, true);
14052            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14053
14054            synchronized (mPackages) {
14055                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14056            }
14057
14058            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14059            serializer.endDocument();
14060            serializer.flush();
14061        } catch (Exception e) {
14062            if (DEBUG_BACKUP) {
14063                Slog.e(TAG, "Unable to write default apps for backup", e);
14064            }
14065            return null;
14066        }
14067
14068        return dataStream.toByteArray();
14069    }
14070
14071    @Override
14072    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14073        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14074            throw new SecurityException("Only the system may call restorePreferredActivities()");
14075        }
14076
14077        try {
14078            final XmlPullParser parser = Xml.newPullParser();
14079            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14080            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14081                    new BlobXmlRestorer() {
14082                        @Override
14083                        public void apply(XmlPullParser parser, int userId)
14084                                throws XmlPullParserException, IOException {
14085                            synchronized (mPackages) {
14086                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14087                                mSettings.writeLPr();
14088                            }
14089                        }
14090                    } );
14091        } catch (Exception e) {
14092            if (DEBUG_BACKUP) {
14093                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14094            }
14095        }
14096    }
14097
14098    @Override
14099    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14100            int sourceUserId, int targetUserId, int flags) {
14101        mContext.enforceCallingOrSelfPermission(
14102                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14103        int callingUid = Binder.getCallingUid();
14104        enforceOwnerRights(ownerPackage, callingUid);
14105        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14106        if (intentFilter.countActions() == 0) {
14107            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14108            return;
14109        }
14110        synchronized (mPackages) {
14111            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14112                    ownerPackage, targetUserId, flags);
14113            CrossProfileIntentResolver resolver =
14114                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14115            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14116            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14117            if (existing != null) {
14118                int size = existing.size();
14119                for (int i = 0; i < size; i++) {
14120                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14121                        return;
14122                    }
14123                }
14124            }
14125            resolver.addFilter(newFilter);
14126            scheduleWritePackageRestrictionsLocked(sourceUserId);
14127        }
14128    }
14129
14130    @Override
14131    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14132        mContext.enforceCallingOrSelfPermission(
14133                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14134        int callingUid = Binder.getCallingUid();
14135        enforceOwnerRights(ownerPackage, callingUid);
14136        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14137        synchronized (mPackages) {
14138            CrossProfileIntentResolver resolver =
14139                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14140            ArraySet<CrossProfileIntentFilter> set =
14141                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14142            for (CrossProfileIntentFilter filter : set) {
14143                if (filter.getOwnerPackage().equals(ownerPackage)) {
14144                    resolver.removeFilter(filter);
14145                }
14146            }
14147            scheduleWritePackageRestrictionsLocked(sourceUserId);
14148        }
14149    }
14150
14151    // Enforcing that callingUid is owning pkg on userId
14152    private void enforceOwnerRights(String pkg, int callingUid) {
14153        // The system owns everything.
14154        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14155            return;
14156        }
14157        int callingUserId = UserHandle.getUserId(callingUid);
14158        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14159        if (pi == null) {
14160            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14161                    + callingUserId);
14162        }
14163        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14164            throw new SecurityException("Calling uid " + callingUid
14165                    + " does not own package " + pkg);
14166        }
14167    }
14168
14169    @Override
14170    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14171        Intent intent = new Intent(Intent.ACTION_MAIN);
14172        intent.addCategory(Intent.CATEGORY_HOME);
14173
14174        final int callingUserId = UserHandle.getCallingUserId();
14175        List<ResolveInfo> list = queryIntentActivities(intent, null,
14176                PackageManager.GET_META_DATA, callingUserId);
14177        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14178                true, false, false, callingUserId);
14179
14180        allHomeCandidates.clear();
14181        if (list != null) {
14182            for (ResolveInfo ri : list) {
14183                allHomeCandidates.add(ri);
14184            }
14185        }
14186        return (preferred == null || preferred.activityInfo == null)
14187                ? null
14188                : new ComponentName(preferred.activityInfo.packageName,
14189                        preferred.activityInfo.name);
14190    }
14191
14192    @Override
14193    public void setApplicationEnabledSetting(String appPackageName,
14194            int newState, int flags, int userId, String callingPackage) {
14195        if (!sUserManager.exists(userId)) return;
14196        if (callingPackage == null) {
14197            callingPackage = Integer.toString(Binder.getCallingUid());
14198        }
14199        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14200    }
14201
14202    @Override
14203    public void setComponentEnabledSetting(ComponentName componentName,
14204            int newState, int flags, int userId) {
14205        if (!sUserManager.exists(userId)) return;
14206        setEnabledSetting(componentName.getPackageName(),
14207                componentName.getClassName(), newState, flags, userId, null);
14208    }
14209
14210    private void setEnabledSetting(final String packageName, String className, int newState,
14211            final int flags, int userId, String callingPackage) {
14212        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14213              || newState == COMPONENT_ENABLED_STATE_ENABLED
14214              || newState == COMPONENT_ENABLED_STATE_DISABLED
14215              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14216              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14217            throw new IllegalArgumentException("Invalid new component state: "
14218                    + newState);
14219        }
14220        PackageSetting pkgSetting;
14221        final int uid = Binder.getCallingUid();
14222        final int permission = mContext.checkCallingOrSelfPermission(
14223                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14224        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14225        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14226        boolean sendNow = false;
14227        boolean isApp = (className == null);
14228        String componentName = isApp ? packageName : className;
14229        int packageUid = -1;
14230        ArrayList<String> components;
14231
14232        // writer
14233        synchronized (mPackages) {
14234            pkgSetting = mSettings.mPackages.get(packageName);
14235            if (pkgSetting == null) {
14236                if (className == null) {
14237                    throw new IllegalArgumentException(
14238                            "Unknown package: " + packageName);
14239                }
14240                throw new IllegalArgumentException(
14241                        "Unknown component: " + packageName
14242                        + "/" + className);
14243            }
14244            // Allow root and verify that userId is not being specified by a different user
14245            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14246                throw new SecurityException(
14247                        "Permission Denial: attempt to change component state from pid="
14248                        + Binder.getCallingPid()
14249                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14250            }
14251            if (className == null) {
14252                // We're dealing with an application/package level state change
14253                if (pkgSetting.getEnabled(userId) == newState) {
14254                    // Nothing to do
14255                    return;
14256                }
14257                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14258                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14259                    // Don't care about who enables an app.
14260                    callingPackage = null;
14261                }
14262                pkgSetting.setEnabled(newState, userId, callingPackage);
14263                // pkgSetting.pkg.mSetEnabled = newState;
14264            } else {
14265                // We're dealing with a component level state change
14266                // First, verify that this is a valid class name.
14267                PackageParser.Package pkg = pkgSetting.pkg;
14268                if (pkg == null || !pkg.hasComponentClassName(className)) {
14269                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14270                        throw new IllegalArgumentException("Component class " + className
14271                                + " does not exist in " + packageName);
14272                    } else {
14273                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14274                                + className + " does not exist in " + packageName);
14275                    }
14276                }
14277                switch (newState) {
14278                case COMPONENT_ENABLED_STATE_ENABLED:
14279                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14280                        return;
14281                    }
14282                    break;
14283                case COMPONENT_ENABLED_STATE_DISABLED:
14284                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14285                        return;
14286                    }
14287                    break;
14288                case COMPONENT_ENABLED_STATE_DEFAULT:
14289                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14290                        return;
14291                    }
14292                    break;
14293                default:
14294                    Slog.e(TAG, "Invalid new component state: " + newState);
14295                    return;
14296                }
14297            }
14298            scheduleWritePackageRestrictionsLocked(userId);
14299            components = mPendingBroadcasts.get(userId, packageName);
14300            final boolean newPackage = components == null;
14301            if (newPackage) {
14302                components = new ArrayList<String>();
14303            }
14304            if (!components.contains(componentName)) {
14305                components.add(componentName);
14306            }
14307            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14308                sendNow = true;
14309                // Purge entry from pending broadcast list if another one exists already
14310                // since we are sending one right away.
14311                mPendingBroadcasts.remove(userId, packageName);
14312            } else {
14313                if (newPackage) {
14314                    mPendingBroadcasts.put(userId, packageName, components);
14315                }
14316                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14317                    // Schedule a message
14318                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14319                }
14320            }
14321        }
14322
14323        long callingId = Binder.clearCallingIdentity();
14324        try {
14325            if (sendNow) {
14326                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14327                sendPackageChangedBroadcast(packageName,
14328                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14329            }
14330        } finally {
14331            Binder.restoreCallingIdentity(callingId);
14332        }
14333    }
14334
14335    private void sendPackageChangedBroadcast(String packageName,
14336            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14337        if (DEBUG_INSTALL)
14338            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14339                    + componentNames);
14340        Bundle extras = new Bundle(4);
14341        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14342        String nameList[] = new String[componentNames.size()];
14343        componentNames.toArray(nameList);
14344        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14345        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14346        extras.putInt(Intent.EXTRA_UID, packageUid);
14347        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14348                new int[] {UserHandle.getUserId(packageUid)});
14349    }
14350
14351    @Override
14352    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14353        if (!sUserManager.exists(userId)) return;
14354        final int uid = Binder.getCallingUid();
14355        final int permission = mContext.checkCallingOrSelfPermission(
14356                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14357        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14358        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14359        // writer
14360        synchronized (mPackages) {
14361            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14362                    allowedByPermission, uid, userId)) {
14363                scheduleWritePackageRestrictionsLocked(userId);
14364            }
14365        }
14366    }
14367
14368    @Override
14369    public String getInstallerPackageName(String packageName) {
14370        // reader
14371        synchronized (mPackages) {
14372            return mSettings.getInstallerPackageNameLPr(packageName);
14373        }
14374    }
14375
14376    @Override
14377    public int getApplicationEnabledSetting(String packageName, int userId) {
14378        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14379        int uid = Binder.getCallingUid();
14380        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14381        // reader
14382        synchronized (mPackages) {
14383            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14384        }
14385    }
14386
14387    @Override
14388    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14389        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14390        int uid = Binder.getCallingUid();
14391        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14392        // reader
14393        synchronized (mPackages) {
14394            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14395        }
14396    }
14397
14398    @Override
14399    public void enterSafeMode() {
14400        enforceSystemOrRoot("Only the system can request entering safe mode");
14401
14402        if (!mSystemReady) {
14403            mSafeMode = true;
14404        }
14405    }
14406
14407    @Override
14408    public void systemReady() {
14409        mSystemReady = true;
14410
14411        // Read the compatibilty setting when the system is ready.
14412        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14413                mContext.getContentResolver(),
14414                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14415        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14416        if (DEBUG_SETTINGS) {
14417            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14418        }
14419
14420        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14421
14422        synchronized (mPackages) {
14423            // Verify that all of the preferred activity components actually
14424            // exist.  It is possible for applications to be updated and at
14425            // that point remove a previously declared activity component that
14426            // had been set as a preferred activity.  We try to clean this up
14427            // the next time we encounter that preferred activity, but it is
14428            // possible for the user flow to never be able to return to that
14429            // situation so here we do a sanity check to make sure we haven't
14430            // left any junk around.
14431            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14432            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14433                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14434                removed.clear();
14435                for (PreferredActivity pa : pir.filterSet()) {
14436                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14437                        removed.add(pa);
14438                    }
14439                }
14440                if (removed.size() > 0) {
14441                    for (int r=0; r<removed.size(); r++) {
14442                        PreferredActivity pa = removed.get(r);
14443                        Slog.w(TAG, "Removing dangling preferred activity: "
14444                                + pa.mPref.mComponent);
14445                        pir.removeFilter(pa);
14446                    }
14447                    mSettings.writePackageRestrictionsLPr(
14448                            mSettings.mPreferredActivities.keyAt(i));
14449                }
14450            }
14451
14452            for (int userId : UserManagerService.getInstance().getUserIds()) {
14453                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14454                    grantPermissionsUserIds = ArrayUtils.appendInt(
14455                            grantPermissionsUserIds, userId);
14456                }
14457            }
14458        }
14459        sUserManager.systemReady();
14460
14461        // If we upgraded grant all default permissions before kicking off.
14462        for (int userId : grantPermissionsUserIds) {
14463            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14464        }
14465
14466        // Kick off any messages waiting for system ready
14467        if (mPostSystemReadyMessages != null) {
14468            for (Message msg : mPostSystemReadyMessages) {
14469                msg.sendToTarget();
14470            }
14471            mPostSystemReadyMessages = null;
14472        }
14473
14474        // Watch for external volumes that come and go over time
14475        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14476        storage.registerListener(mStorageListener);
14477
14478        mInstallerService.systemReady();
14479        mPackageDexOptimizer.systemReady();
14480
14481        MountServiceInternal mountServiceInternal = LocalServices.getService(
14482                MountServiceInternal.class);
14483        mountServiceInternal.addExternalStoragePolicy(
14484                new MountServiceInternal.ExternalStorageMountPolicy() {
14485            @Override
14486            public int getMountMode(int uid, String packageName) {
14487                if (Process.isIsolated(uid)) {
14488                    return Zygote.MOUNT_EXTERNAL_NONE;
14489                }
14490                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14491                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14492                }
14493                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14494                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14495                }
14496                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14497                    return Zygote.MOUNT_EXTERNAL_READ;
14498                }
14499                return Zygote.MOUNT_EXTERNAL_WRITE;
14500            }
14501
14502            @Override
14503            public boolean hasExternalStorage(int uid, String packageName) {
14504                return true;
14505            }
14506        });
14507    }
14508
14509    @Override
14510    public boolean isSafeMode() {
14511        return mSafeMode;
14512    }
14513
14514    @Override
14515    public boolean hasSystemUidErrors() {
14516        return mHasSystemUidErrors;
14517    }
14518
14519    static String arrayToString(int[] array) {
14520        StringBuffer buf = new StringBuffer(128);
14521        buf.append('[');
14522        if (array != null) {
14523            for (int i=0; i<array.length; i++) {
14524                if (i > 0) buf.append(", ");
14525                buf.append(array[i]);
14526            }
14527        }
14528        buf.append(']');
14529        return buf.toString();
14530    }
14531
14532    static class DumpState {
14533        public static final int DUMP_LIBS = 1 << 0;
14534        public static final int DUMP_FEATURES = 1 << 1;
14535        public static final int DUMP_RESOLVERS = 1 << 2;
14536        public static final int DUMP_PERMISSIONS = 1 << 3;
14537        public static final int DUMP_PACKAGES = 1 << 4;
14538        public static final int DUMP_SHARED_USERS = 1 << 5;
14539        public static final int DUMP_MESSAGES = 1 << 6;
14540        public static final int DUMP_PROVIDERS = 1 << 7;
14541        public static final int DUMP_VERIFIERS = 1 << 8;
14542        public static final int DUMP_PREFERRED = 1 << 9;
14543        public static final int DUMP_PREFERRED_XML = 1 << 10;
14544        public static final int DUMP_KEYSETS = 1 << 11;
14545        public static final int DUMP_VERSION = 1 << 12;
14546        public static final int DUMP_INSTALLS = 1 << 13;
14547        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14548        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14549
14550        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14551
14552        private int mTypes;
14553
14554        private int mOptions;
14555
14556        private boolean mTitlePrinted;
14557
14558        private SharedUserSetting mSharedUser;
14559
14560        public boolean isDumping(int type) {
14561            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14562                return true;
14563            }
14564
14565            return (mTypes & type) != 0;
14566        }
14567
14568        public void setDump(int type) {
14569            mTypes |= type;
14570        }
14571
14572        public boolean isOptionEnabled(int option) {
14573            return (mOptions & option) != 0;
14574        }
14575
14576        public void setOptionEnabled(int option) {
14577            mOptions |= option;
14578        }
14579
14580        public boolean onTitlePrinted() {
14581            final boolean printed = mTitlePrinted;
14582            mTitlePrinted = true;
14583            return printed;
14584        }
14585
14586        public boolean getTitlePrinted() {
14587            return mTitlePrinted;
14588        }
14589
14590        public void setTitlePrinted(boolean enabled) {
14591            mTitlePrinted = enabled;
14592        }
14593
14594        public SharedUserSetting getSharedUser() {
14595            return mSharedUser;
14596        }
14597
14598        public void setSharedUser(SharedUserSetting user) {
14599            mSharedUser = user;
14600        }
14601    }
14602
14603    @Override
14604    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14605        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14606                != PackageManager.PERMISSION_GRANTED) {
14607            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14608                    + Binder.getCallingPid()
14609                    + ", uid=" + Binder.getCallingUid()
14610                    + " without permission "
14611                    + android.Manifest.permission.DUMP);
14612            return;
14613        }
14614
14615        DumpState dumpState = new DumpState();
14616        boolean fullPreferred = false;
14617        boolean checkin = false;
14618
14619        String packageName = null;
14620        ArraySet<String> permissionNames = null;
14621
14622        int opti = 0;
14623        while (opti < args.length) {
14624            String opt = args[opti];
14625            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14626                break;
14627            }
14628            opti++;
14629
14630            if ("-a".equals(opt)) {
14631                // Right now we only know how to print all.
14632            } else if ("-h".equals(opt)) {
14633                pw.println("Package manager dump options:");
14634                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14635                pw.println("    --checkin: dump for a checkin");
14636                pw.println("    -f: print details of intent filters");
14637                pw.println("    -h: print this help");
14638                pw.println("  cmd may be one of:");
14639                pw.println("    l[ibraries]: list known shared libraries");
14640                pw.println("    f[ibraries]: list device features");
14641                pw.println("    k[eysets]: print known keysets");
14642                pw.println("    r[esolvers]: dump intent resolvers");
14643                pw.println("    perm[issions]: dump permissions");
14644                pw.println("    permission [name ...]: dump declaration and use of given permission");
14645                pw.println("    pref[erred]: print preferred package settings");
14646                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14647                pw.println("    prov[iders]: dump content providers");
14648                pw.println("    p[ackages]: dump installed packages");
14649                pw.println("    s[hared-users]: dump shared user IDs");
14650                pw.println("    m[essages]: print collected runtime messages");
14651                pw.println("    v[erifiers]: print package verifier info");
14652                pw.println("    version: print database version info");
14653                pw.println("    write: write current settings now");
14654                pw.println("    <package.name>: info about given package");
14655                pw.println("    installs: details about install sessions");
14656                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14657                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14658                return;
14659            } else if ("--checkin".equals(opt)) {
14660                checkin = true;
14661            } else if ("-f".equals(opt)) {
14662                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14663            } else {
14664                pw.println("Unknown argument: " + opt + "; use -h for help");
14665            }
14666        }
14667
14668        // Is the caller requesting to dump a particular piece of data?
14669        if (opti < args.length) {
14670            String cmd = args[opti];
14671            opti++;
14672            // Is this a package name?
14673            if ("android".equals(cmd) || cmd.contains(".")) {
14674                packageName = cmd;
14675                // When dumping a single package, we always dump all of its
14676                // filter information since the amount of data will be reasonable.
14677                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14678            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14679                dumpState.setDump(DumpState.DUMP_LIBS);
14680            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14681                dumpState.setDump(DumpState.DUMP_FEATURES);
14682            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14683                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14684            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14685                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14686            } else if ("permission".equals(cmd)) {
14687                if (opti >= args.length) {
14688                    pw.println("Error: permission requires permission name");
14689                    return;
14690                }
14691                permissionNames = new ArraySet<>();
14692                while (opti < args.length) {
14693                    permissionNames.add(args[opti]);
14694                    opti++;
14695                }
14696                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14697                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14698            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14699                dumpState.setDump(DumpState.DUMP_PREFERRED);
14700            } else if ("preferred-xml".equals(cmd)) {
14701                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14702                if (opti < args.length && "--full".equals(args[opti])) {
14703                    fullPreferred = true;
14704                    opti++;
14705                }
14706            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14707                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14708            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14709                dumpState.setDump(DumpState.DUMP_PACKAGES);
14710            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14711                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14712            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14713                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14714            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14715                dumpState.setDump(DumpState.DUMP_MESSAGES);
14716            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14717                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14718            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14719                    || "intent-filter-verifiers".equals(cmd)) {
14720                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14721            } else if ("version".equals(cmd)) {
14722                dumpState.setDump(DumpState.DUMP_VERSION);
14723            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14724                dumpState.setDump(DumpState.DUMP_KEYSETS);
14725            } else if ("installs".equals(cmd)) {
14726                dumpState.setDump(DumpState.DUMP_INSTALLS);
14727            } else if ("write".equals(cmd)) {
14728                synchronized (mPackages) {
14729                    mSettings.writeLPr();
14730                    pw.println("Settings written.");
14731                    return;
14732                }
14733            }
14734        }
14735
14736        if (checkin) {
14737            pw.println("vers,1");
14738        }
14739
14740        // reader
14741        synchronized (mPackages) {
14742            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14743                if (!checkin) {
14744                    if (dumpState.onTitlePrinted())
14745                        pw.println();
14746                    pw.println("Database versions:");
14747                    pw.print("  SDK Version:");
14748                    pw.print(" internal=");
14749                    pw.print(mSettings.mInternalSdkPlatform);
14750                    pw.print(" external=");
14751                    pw.println(mSettings.mExternalSdkPlatform);
14752                    pw.print("  DB Version:");
14753                    pw.print(" internal=");
14754                    pw.print(mSettings.mInternalDatabaseVersion);
14755                    pw.print(" external=");
14756                    pw.println(mSettings.mExternalDatabaseVersion);
14757                }
14758            }
14759
14760            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14761                if (!checkin) {
14762                    if (dumpState.onTitlePrinted())
14763                        pw.println();
14764                    pw.println("Verifiers:");
14765                    pw.print("  Required: ");
14766                    pw.print(mRequiredVerifierPackage);
14767                    pw.print(" (uid=");
14768                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14769                    pw.println(")");
14770                } else if (mRequiredVerifierPackage != null) {
14771                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14772                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14773                }
14774            }
14775
14776            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14777                    packageName == null) {
14778                if (mIntentFilterVerifierComponent != null) {
14779                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14780                    if (!checkin) {
14781                        if (dumpState.onTitlePrinted())
14782                            pw.println();
14783                        pw.println("Intent Filter Verifier:");
14784                        pw.print("  Using: ");
14785                        pw.print(verifierPackageName);
14786                        pw.print(" (uid=");
14787                        pw.print(getPackageUid(verifierPackageName, 0));
14788                        pw.println(")");
14789                    } else if (verifierPackageName != null) {
14790                        pw.print("ifv,"); pw.print(verifierPackageName);
14791                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14792                    }
14793                } else {
14794                    pw.println();
14795                    pw.println("No Intent Filter Verifier available!");
14796                }
14797            }
14798
14799            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14800                boolean printedHeader = false;
14801                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14802                while (it.hasNext()) {
14803                    String name = it.next();
14804                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14805                    if (!checkin) {
14806                        if (!printedHeader) {
14807                            if (dumpState.onTitlePrinted())
14808                                pw.println();
14809                            pw.println("Libraries:");
14810                            printedHeader = true;
14811                        }
14812                        pw.print("  ");
14813                    } else {
14814                        pw.print("lib,");
14815                    }
14816                    pw.print(name);
14817                    if (!checkin) {
14818                        pw.print(" -> ");
14819                    }
14820                    if (ent.path != null) {
14821                        if (!checkin) {
14822                            pw.print("(jar) ");
14823                            pw.print(ent.path);
14824                        } else {
14825                            pw.print(",jar,");
14826                            pw.print(ent.path);
14827                        }
14828                    } else {
14829                        if (!checkin) {
14830                            pw.print("(apk) ");
14831                            pw.print(ent.apk);
14832                        } else {
14833                            pw.print(",apk,");
14834                            pw.print(ent.apk);
14835                        }
14836                    }
14837                    pw.println();
14838                }
14839            }
14840
14841            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14842                if (dumpState.onTitlePrinted())
14843                    pw.println();
14844                if (!checkin) {
14845                    pw.println("Features:");
14846                }
14847                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14848                while (it.hasNext()) {
14849                    String name = it.next();
14850                    if (!checkin) {
14851                        pw.print("  ");
14852                    } else {
14853                        pw.print("feat,");
14854                    }
14855                    pw.println(name);
14856                }
14857            }
14858
14859            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14860                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14861                        : "Activity Resolver Table:", "  ", packageName,
14862                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14863                    dumpState.setTitlePrinted(true);
14864                }
14865                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14866                        : "Receiver Resolver Table:", "  ", packageName,
14867                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14868                    dumpState.setTitlePrinted(true);
14869                }
14870                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14871                        : "Service Resolver Table:", "  ", packageName,
14872                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14873                    dumpState.setTitlePrinted(true);
14874                }
14875                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14876                        : "Provider Resolver Table:", "  ", packageName,
14877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14878                    dumpState.setTitlePrinted(true);
14879                }
14880            }
14881
14882            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14883                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14884                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14885                    int user = mSettings.mPreferredActivities.keyAt(i);
14886                    if (pir.dump(pw,
14887                            dumpState.getTitlePrinted()
14888                                ? "\nPreferred Activities User " + user + ":"
14889                                : "Preferred Activities User " + user + ":", "  ",
14890                            packageName, true, false)) {
14891                        dumpState.setTitlePrinted(true);
14892                    }
14893                }
14894            }
14895
14896            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14897                pw.flush();
14898                FileOutputStream fout = new FileOutputStream(fd);
14899                BufferedOutputStream str = new BufferedOutputStream(fout);
14900                XmlSerializer serializer = new FastXmlSerializer();
14901                try {
14902                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14903                    serializer.startDocument(null, true);
14904                    serializer.setFeature(
14905                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14906                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14907                    serializer.endDocument();
14908                    serializer.flush();
14909                } catch (IllegalArgumentException e) {
14910                    pw.println("Failed writing: " + e);
14911                } catch (IllegalStateException e) {
14912                    pw.println("Failed writing: " + e);
14913                } catch (IOException e) {
14914                    pw.println("Failed writing: " + e);
14915                }
14916            }
14917
14918            if (!checkin
14919                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14920                    && packageName == null) {
14921                pw.println();
14922                int count = mSettings.mPackages.size();
14923                if (count == 0) {
14924                    pw.println("No applications!");
14925                    pw.println();
14926                } else {
14927                    final String prefix = "  ";
14928                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14929                    if (allPackageSettings.size() == 0) {
14930                        pw.println("No domain preferred apps!");
14931                        pw.println();
14932                    } else {
14933                        pw.println("App verification status:");
14934                        pw.println();
14935                        count = 0;
14936                        for (PackageSetting ps : allPackageSettings) {
14937                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14938                            if (ivi == null || ivi.getPackageName() == null) continue;
14939                            pw.println(prefix + "Package: " + ivi.getPackageName());
14940                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14941                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14942                            pw.println();
14943                            count++;
14944                        }
14945                        if (count == 0) {
14946                            pw.println(prefix + "No app verification established.");
14947                            pw.println();
14948                        }
14949                        for (int userId : sUserManager.getUserIds()) {
14950                            pw.println("App linkages for user " + userId + ":");
14951                            pw.println();
14952                            count = 0;
14953                            for (PackageSetting ps : allPackageSettings) {
14954                                final long status = ps.getDomainVerificationStatusForUser(userId);
14955                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14956                                    continue;
14957                                }
14958                                pw.println(prefix + "Package: " + ps.name);
14959                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14960                                String statusStr = IntentFilterVerificationInfo.
14961                                        getStatusStringFromValue(status);
14962                                pw.println(prefix + "Status:  " + statusStr);
14963                                pw.println();
14964                                count++;
14965                            }
14966                            if (count == 0) {
14967                                pw.println(prefix + "No configured app linkages.");
14968                                pw.println();
14969                            }
14970                        }
14971                    }
14972                }
14973            }
14974
14975            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14976                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14977                if (packageName == null && permissionNames == null) {
14978                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14979                        if (iperm == 0) {
14980                            if (dumpState.onTitlePrinted())
14981                                pw.println();
14982                            pw.println("AppOp Permissions:");
14983                        }
14984                        pw.print("  AppOp Permission ");
14985                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14986                        pw.println(":");
14987                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14988                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14989                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14990                        }
14991                    }
14992                }
14993            }
14994
14995            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14996                boolean printedSomething = false;
14997                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14998                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14999                        continue;
15000                    }
15001                    if (!printedSomething) {
15002                        if (dumpState.onTitlePrinted())
15003                            pw.println();
15004                        pw.println("Registered ContentProviders:");
15005                        printedSomething = true;
15006                    }
15007                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15008                    pw.print("    "); pw.println(p.toString());
15009                }
15010                printedSomething = false;
15011                for (Map.Entry<String, PackageParser.Provider> entry :
15012                        mProvidersByAuthority.entrySet()) {
15013                    PackageParser.Provider p = entry.getValue();
15014                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15015                        continue;
15016                    }
15017                    if (!printedSomething) {
15018                        if (dumpState.onTitlePrinted())
15019                            pw.println();
15020                        pw.println("ContentProvider Authorities:");
15021                        printedSomething = true;
15022                    }
15023                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15024                    pw.print("    "); pw.println(p.toString());
15025                    if (p.info != null && p.info.applicationInfo != null) {
15026                        final String appInfo = p.info.applicationInfo.toString();
15027                        pw.print("      applicationInfo="); pw.println(appInfo);
15028                    }
15029                }
15030            }
15031
15032            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15033                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15034            }
15035
15036            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15037                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15038            }
15039
15040            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15041                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15042            }
15043
15044            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15045                // XXX should handle packageName != null by dumping only install data that
15046                // the given package is involved with.
15047                if (dumpState.onTitlePrinted()) pw.println();
15048                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15049            }
15050
15051            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15052                if (dumpState.onTitlePrinted()) pw.println();
15053                mSettings.dumpReadMessagesLPr(pw, dumpState);
15054
15055                pw.println();
15056                pw.println("Package warning messages:");
15057                BufferedReader in = null;
15058                String line = null;
15059                try {
15060                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15061                    while ((line = in.readLine()) != null) {
15062                        if (line.contains("ignored: updated version")) continue;
15063                        pw.println(line);
15064                    }
15065                } catch (IOException ignored) {
15066                } finally {
15067                    IoUtils.closeQuietly(in);
15068                }
15069            }
15070
15071            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15072                BufferedReader in = null;
15073                String line = null;
15074                try {
15075                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15076                    while ((line = in.readLine()) != null) {
15077                        if (line.contains("ignored: updated version")) continue;
15078                        pw.print("msg,");
15079                        pw.println(line);
15080                    }
15081                } catch (IOException ignored) {
15082                } finally {
15083                    IoUtils.closeQuietly(in);
15084                }
15085            }
15086        }
15087    }
15088
15089    private String dumpDomainString(String packageName) {
15090        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15091        List<IntentFilter> filters = getAllIntentFilters(packageName);
15092
15093        ArraySet<String> result = new ArraySet<>();
15094        if (iviList.size() > 0) {
15095            for (IntentFilterVerificationInfo ivi : iviList) {
15096                for (String host : ivi.getDomains()) {
15097                    result.add(host);
15098                }
15099            }
15100        }
15101        if (filters != null && filters.size() > 0) {
15102            for (IntentFilter filter : filters) {
15103                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15104                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15105                    result.addAll(filter.getHostsList());
15106                }
15107            }
15108        }
15109
15110        StringBuilder sb = new StringBuilder(result.size() * 16);
15111        for (String domain : result) {
15112            if (sb.length() > 0) sb.append(" ");
15113            sb.append(domain);
15114        }
15115        return sb.toString();
15116    }
15117
15118    // ------- apps on sdcard specific code -------
15119    static final boolean DEBUG_SD_INSTALL = false;
15120
15121    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15122
15123    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15124
15125    private boolean mMediaMounted = false;
15126
15127    static String getEncryptKey() {
15128        try {
15129            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15130                    SD_ENCRYPTION_KEYSTORE_NAME);
15131            if (sdEncKey == null) {
15132                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15133                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15134                if (sdEncKey == null) {
15135                    Slog.e(TAG, "Failed to create encryption keys");
15136                    return null;
15137                }
15138            }
15139            return sdEncKey;
15140        } catch (NoSuchAlgorithmException nsae) {
15141            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15142            return null;
15143        } catch (IOException ioe) {
15144            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15145            return null;
15146        }
15147    }
15148
15149    /*
15150     * Update media status on PackageManager.
15151     */
15152    @Override
15153    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15154        int callingUid = Binder.getCallingUid();
15155        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15156            throw new SecurityException("Media status can only be updated by the system");
15157        }
15158        // reader; this apparently protects mMediaMounted, but should probably
15159        // be a different lock in that case.
15160        synchronized (mPackages) {
15161            Log.i(TAG, "Updating external media status from "
15162                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15163                    + (mediaStatus ? "mounted" : "unmounted"));
15164            if (DEBUG_SD_INSTALL)
15165                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15166                        + ", mMediaMounted=" + mMediaMounted);
15167            if (mediaStatus == mMediaMounted) {
15168                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15169                        : 0, -1);
15170                mHandler.sendMessage(msg);
15171                return;
15172            }
15173            mMediaMounted = mediaStatus;
15174        }
15175        // Queue up an async operation since the package installation may take a
15176        // little while.
15177        mHandler.post(new Runnable() {
15178            public void run() {
15179                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15180            }
15181        });
15182    }
15183
15184    /**
15185     * Called by MountService when the initial ASECs to scan are available.
15186     * Should block until all the ASEC containers are finished being scanned.
15187     */
15188    public void scanAvailableAsecs() {
15189        updateExternalMediaStatusInner(true, false, false);
15190        if (mShouldRestoreconData) {
15191            SELinuxMMAC.setRestoreconDone();
15192            mShouldRestoreconData = false;
15193        }
15194    }
15195
15196    /*
15197     * Collect information of applications on external media, map them against
15198     * existing containers and update information based on current mount status.
15199     * Please note that we always have to report status if reportStatus has been
15200     * set to true especially when unloading packages.
15201     */
15202    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15203            boolean externalStorage) {
15204        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15205        int[] uidArr = EmptyArray.INT;
15206
15207        final String[] list = PackageHelper.getSecureContainerList();
15208        if (ArrayUtils.isEmpty(list)) {
15209            Log.i(TAG, "No secure containers found");
15210        } else {
15211            // Process list of secure containers and categorize them
15212            // as active or stale based on their package internal state.
15213
15214            // reader
15215            synchronized (mPackages) {
15216                for (String cid : list) {
15217                    // Leave stages untouched for now; installer service owns them
15218                    if (PackageInstallerService.isStageName(cid)) continue;
15219
15220                    if (DEBUG_SD_INSTALL)
15221                        Log.i(TAG, "Processing container " + cid);
15222                    String pkgName = getAsecPackageName(cid);
15223                    if (pkgName == null) {
15224                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15225                        continue;
15226                    }
15227                    if (DEBUG_SD_INSTALL)
15228                        Log.i(TAG, "Looking for pkg : " + pkgName);
15229
15230                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15231                    if (ps == null) {
15232                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15233                        continue;
15234                    }
15235
15236                    /*
15237                     * Skip packages that are not external if we're unmounting
15238                     * external storage.
15239                     */
15240                    if (externalStorage && !isMounted && !isExternal(ps)) {
15241                        continue;
15242                    }
15243
15244                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15245                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15246                    // The package status is changed only if the code path
15247                    // matches between settings and the container id.
15248                    if (ps.codePathString != null
15249                            && ps.codePathString.startsWith(args.getCodePath())) {
15250                        if (DEBUG_SD_INSTALL) {
15251                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15252                                    + " at code path: " + ps.codePathString);
15253                        }
15254
15255                        // We do have a valid package installed on sdcard
15256                        processCids.put(args, ps.codePathString);
15257                        final int uid = ps.appId;
15258                        if (uid != -1) {
15259                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15260                        }
15261                    } else {
15262                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15263                                + ps.codePathString);
15264                    }
15265                }
15266            }
15267
15268            Arrays.sort(uidArr);
15269        }
15270
15271        // Process packages with valid entries.
15272        if (isMounted) {
15273            if (DEBUG_SD_INSTALL)
15274                Log.i(TAG, "Loading packages");
15275            loadMediaPackages(processCids, uidArr);
15276            startCleaningPackages();
15277            mInstallerService.onSecureContainersAvailable();
15278        } else {
15279            if (DEBUG_SD_INSTALL)
15280                Log.i(TAG, "Unloading packages");
15281            unloadMediaPackages(processCids, uidArr, reportStatus);
15282        }
15283    }
15284
15285    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15286            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15287        final int size = infos.size();
15288        final String[] packageNames = new String[size];
15289        final int[] packageUids = new int[size];
15290        for (int i = 0; i < size; i++) {
15291            final ApplicationInfo info = infos.get(i);
15292            packageNames[i] = info.packageName;
15293            packageUids[i] = info.uid;
15294        }
15295        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15296                finishedReceiver);
15297    }
15298
15299    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15300            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15301        sendResourcesChangedBroadcast(mediaStatus, replacing,
15302                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15303    }
15304
15305    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15306            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15307        int size = pkgList.length;
15308        if (size > 0) {
15309            // Send broadcasts here
15310            Bundle extras = new Bundle();
15311            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15312            if (uidArr != null) {
15313                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15314            }
15315            if (replacing) {
15316                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15317            }
15318            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15319                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15320            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15321        }
15322    }
15323
15324   /*
15325     * Look at potentially valid container ids from processCids If package
15326     * information doesn't match the one on record or package scanning fails,
15327     * the cid is added to list of removeCids. We currently don't delete stale
15328     * containers.
15329     */
15330    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15331        ArrayList<String> pkgList = new ArrayList<String>();
15332        Set<AsecInstallArgs> keys = processCids.keySet();
15333
15334        for (AsecInstallArgs args : keys) {
15335            String codePath = processCids.get(args);
15336            if (DEBUG_SD_INSTALL)
15337                Log.i(TAG, "Loading container : " + args.cid);
15338            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15339            try {
15340                // Make sure there are no container errors first.
15341                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15342                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15343                            + " when installing from sdcard");
15344                    continue;
15345                }
15346                // Check code path here.
15347                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15348                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15349                            + " does not match one in settings " + codePath);
15350                    continue;
15351                }
15352                // Parse package
15353                int parseFlags = mDefParseFlags;
15354                if (args.isExternalAsec()) {
15355                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15356                }
15357                if (args.isFwdLocked()) {
15358                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15359                }
15360
15361                synchronized (mInstallLock) {
15362                    PackageParser.Package pkg = null;
15363                    try {
15364                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15365                    } catch (PackageManagerException e) {
15366                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15367                    }
15368                    // Scan the package
15369                    if (pkg != null) {
15370                        /*
15371                         * TODO why is the lock being held? doPostInstall is
15372                         * called in other places without the lock. This needs
15373                         * to be straightened out.
15374                         */
15375                        // writer
15376                        synchronized (mPackages) {
15377                            retCode = PackageManager.INSTALL_SUCCEEDED;
15378                            pkgList.add(pkg.packageName);
15379                            // Post process args
15380                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15381                                    pkg.applicationInfo.uid);
15382                        }
15383                    } else {
15384                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15385                    }
15386                }
15387
15388            } finally {
15389                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15390                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15391                }
15392            }
15393        }
15394        // writer
15395        synchronized (mPackages) {
15396            // If the platform SDK has changed since the last time we booted,
15397            // we need to re-grant app permission to catch any new ones that
15398            // appear. This is really a hack, and means that apps can in some
15399            // cases get permissions that the user didn't initially explicitly
15400            // allow... it would be nice to have some better way to handle
15401            // this situation.
15402            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15403            if (regrantPermissions)
15404                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15405                        + mSdkVersion + "; regranting permissions for external storage");
15406            mSettings.mExternalSdkPlatform = mSdkVersion;
15407
15408            // Make sure group IDs have been assigned, and any permission
15409            // changes in other apps are accounted for
15410            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15411                    | (regrantPermissions
15412                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15413                            : 0));
15414
15415            mSettings.updateExternalDatabaseVersion();
15416
15417            // can downgrade to reader
15418            // Persist settings
15419            mSettings.writeLPr();
15420        }
15421        // Send a broadcast to let everyone know we are done processing
15422        if (pkgList.size() > 0) {
15423            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15424        }
15425    }
15426
15427   /*
15428     * Utility method to unload a list of specified containers
15429     */
15430    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15431        // Just unmount all valid containers.
15432        for (AsecInstallArgs arg : cidArgs) {
15433            synchronized (mInstallLock) {
15434                arg.doPostDeleteLI(false);
15435           }
15436       }
15437   }
15438
15439    /*
15440     * Unload packages mounted on external media. This involves deleting package
15441     * data from internal structures, sending broadcasts about diabled packages,
15442     * gc'ing to free up references, unmounting all secure containers
15443     * corresponding to packages on external media, and posting a
15444     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15445     * that we always have to post this message if status has been requested no
15446     * matter what.
15447     */
15448    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15449            final boolean reportStatus) {
15450        if (DEBUG_SD_INSTALL)
15451            Log.i(TAG, "unloading media packages");
15452        ArrayList<String> pkgList = new ArrayList<String>();
15453        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15454        final Set<AsecInstallArgs> keys = processCids.keySet();
15455        for (AsecInstallArgs args : keys) {
15456            String pkgName = args.getPackageName();
15457            if (DEBUG_SD_INSTALL)
15458                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15459            // Delete package internally
15460            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15461            synchronized (mInstallLock) {
15462                boolean res = deletePackageLI(pkgName, null, false, null, null,
15463                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15464                if (res) {
15465                    pkgList.add(pkgName);
15466                } else {
15467                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15468                    failedList.add(args);
15469                }
15470            }
15471        }
15472
15473        // reader
15474        synchronized (mPackages) {
15475            // We didn't update the settings after removing each package;
15476            // write them now for all packages.
15477            mSettings.writeLPr();
15478        }
15479
15480        // We have to absolutely send UPDATED_MEDIA_STATUS only
15481        // after confirming that all the receivers processed the ordered
15482        // broadcast when packages get disabled, force a gc to clean things up.
15483        // and unload all the containers.
15484        if (pkgList.size() > 0) {
15485            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15486                    new IIntentReceiver.Stub() {
15487                public void performReceive(Intent intent, int resultCode, String data,
15488                        Bundle extras, boolean ordered, boolean sticky,
15489                        int sendingUser) throws RemoteException {
15490                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15491                            reportStatus ? 1 : 0, 1, keys);
15492                    mHandler.sendMessage(msg);
15493                }
15494            });
15495        } else {
15496            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15497                    keys);
15498            mHandler.sendMessage(msg);
15499        }
15500    }
15501
15502    private void loadPrivatePackages(VolumeInfo vol) {
15503        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15504        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15505        synchronized (mInstallLock) {
15506        synchronized (mPackages) {
15507            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15508            for (PackageSetting ps : packages) {
15509                final PackageParser.Package pkg;
15510                try {
15511                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15512                    loaded.add(pkg.applicationInfo);
15513                } catch (PackageManagerException e) {
15514                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15515                }
15516            }
15517
15518            // TODO: regrant any permissions that changed based since original install
15519
15520            mSettings.writeLPr();
15521        }
15522        }
15523
15524        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15525        sendResourcesChangedBroadcast(true, false, loaded, null);
15526    }
15527
15528    private void unloadPrivatePackages(VolumeInfo vol) {
15529        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15530        synchronized (mInstallLock) {
15531        synchronized (mPackages) {
15532            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15533            for (PackageSetting ps : packages) {
15534                if (ps.pkg == null) continue;
15535
15536                final ApplicationInfo info = ps.pkg.applicationInfo;
15537                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15538                if (deletePackageLI(ps.name, null, false, null, null,
15539                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15540                    unloaded.add(info);
15541                } else {
15542                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15543                }
15544            }
15545
15546            mSettings.writeLPr();
15547        }
15548        }
15549
15550        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15551        sendResourcesChangedBroadcast(false, false, unloaded, null);
15552    }
15553
15554    /**
15555     * Examine all users present on given mounted volume, and destroy data
15556     * belonging to users that are no longer valid, or whose user ID has been
15557     * recycled.
15558     */
15559    private void reconcileUsers(String volumeUuid) {
15560        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15561        if (ArrayUtils.isEmpty(files)) {
15562            Slog.d(TAG, "No users found on " + volumeUuid);
15563            return;
15564        }
15565
15566        for (File file : files) {
15567            if (!file.isDirectory()) continue;
15568
15569            final int userId;
15570            final UserInfo info;
15571            try {
15572                userId = Integer.parseInt(file.getName());
15573                info = sUserManager.getUserInfo(userId);
15574            } catch (NumberFormatException e) {
15575                Slog.w(TAG, "Invalid user directory " + file);
15576                continue;
15577            }
15578
15579            boolean destroyUser = false;
15580            if (info == null) {
15581                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15582                        + " because no matching user was found");
15583                destroyUser = true;
15584            } else {
15585                try {
15586                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15587                } catch (IOException e) {
15588                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15589                            + " because we failed to enforce serial number: " + e);
15590                    destroyUser = true;
15591                }
15592            }
15593
15594            if (destroyUser) {
15595                synchronized (mInstallLock) {
15596                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15597                }
15598            }
15599        }
15600
15601        final UserManager um = mContext.getSystemService(UserManager.class);
15602        for (UserInfo user : um.getUsers()) {
15603            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15604            if (userDir.exists()) continue;
15605
15606            try {
15607                UserManagerService.prepareUserDirectory(userDir);
15608                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15609            } catch (IOException e) {
15610                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15611            }
15612        }
15613    }
15614
15615    /**
15616     * Examine all apps present on given mounted volume, and destroy apps that
15617     * aren't expected, either due to uninstallation or reinstallation on
15618     * another volume.
15619     */
15620    private void reconcileApps(String volumeUuid) {
15621        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15622        if (ArrayUtils.isEmpty(files)) {
15623            Slog.d(TAG, "No apps found on " + volumeUuid);
15624            return;
15625        }
15626
15627        for (File file : files) {
15628            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15629                    && !PackageInstallerService.isStageName(file.getName());
15630            if (!isPackage) {
15631                // Ignore entries which are not packages
15632                continue;
15633            }
15634
15635            boolean destroyApp = false;
15636            String packageName = null;
15637            try {
15638                final PackageLite pkg = PackageParser.parsePackageLite(file,
15639                        PackageParser.PARSE_MUST_BE_APK);
15640                packageName = pkg.packageName;
15641
15642                synchronized (mPackages) {
15643                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15644                    if (ps == null) {
15645                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15646                                + volumeUuid + " because we found no install record");
15647                        destroyApp = true;
15648                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15649                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15650                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15651                        destroyApp = true;
15652                    }
15653                }
15654
15655            } catch (PackageParserException e) {
15656                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15657                destroyApp = true;
15658            }
15659
15660            if (destroyApp) {
15661                synchronized (mInstallLock) {
15662                    if (packageName != null) {
15663                        removeDataDirsLI(volumeUuid, packageName);
15664                    }
15665                    if (file.isDirectory()) {
15666                        mInstaller.rmPackageDir(file.getAbsolutePath());
15667                    } else {
15668                        file.delete();
15669                    }
15670                }
15671            }
15672        }
15673    }
15674
15675    private void unfreezePackage(String packageName) {
15676        synchronized (mPackages) {
15677            final PackageSetting ps = mSettings.mPackages.get(packageName);
15678            if (ps != null) {
15679                ps.frozen = false;
15680            }
15681        }
15682    }
15683
15684    @Override
15685    public int movePackage(final String packageName, final String volumeUuid) {
15686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15687
15688        final int moveId = mNextMoveId.getAndIncrement();
15689        try {
15690            movePackageInternal(packageName, volumeUuid, moveId);
15691        } catch (PackageManagerException e) {
15692            Slog.w(TAG, "Failed to move " + packageName, e);
15693            mMoveCallbacks.notifyStatusChanged(moveId,
15694                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15695        }
15696        return moveId;
15697    }
15698
15699    private void movePackageInternal(final String packageName, final String volumeUuid,
15700            final int moveId) throws PackageManagerException {
15701        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15702        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15703        final PackageManager pm = mContext.getPackageManager();
15704
15705        final boolean currentAsec;
15706        final String currentVolumeUuid;
15707        final File codeFile;
15708        final String installerPackageName;
15709        final String packageAbiOverride;
15710        final int appId;
15711        final String seinfo;
15712        final String label;
15713
15714        // reader
15715        synchronized (mPackages) {
15716            final PackageParser.Package pkg = mPackages.get(packageName);
15717            final PackageSetting ps = mSettings.mPackages.get(packageName);
15718            if (pkg == null || ps == null) {
15719                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15720            }
15721
15722            if (pkg.applicationInfo.isSystemApp()) {
15723                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15724                        "Cannot move system application");
15725            }
15726
15727            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15728                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15729                        "Package already moved to " + volumeUuid);
15730            }
15731
15732            final File probe = new File(pkg.codePath);
15733            final File probeOat = new File(probe, "oat");
15734            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15735                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15736                        "Move only supported for modern cluster style installs");
15737            }
15738
15739            if (ps.frozen) {
15740                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15741                        "Failed to move already frozen package");
15742            }
15743            ps.frozen = true;
15744
15745            currentAsec = pkg.applicationInfo.isForwardLocked()
15746                    || pkg.applicationInfo.isExternalAsec();
15747            currentVolumeUuid = ps.volumeUuid;
15748            codeFile = new File(pkg.codePath);
15749            installerPackageName = ps.installerPackageName;
15750            packageAbiOverride = ps.cpuAbiOverrideString;
15751            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15752            seinfo = pkg.applicationInfo.seinfo;
15753            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15754        }
15755
15756        // Now that we're guarded by frozen state, kill app during move
15757        killApplication(packageName, appId, "move pkg");
15758
15759        final Bundle extras = new Bundle();
15760        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15761        extras.putString(Intent.EXTRA_TITLE, label);
15762        mMoveCallbacks.notifyCreated(moveId, extras);
15763
15764        int installFlags;
15765        final boolean moveCompleteApp;
15766        final File measurePath;
15767
15768        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15769            installFlags = INSTALL_INTERNAL;
15770            moveCompleteApp = !currentAsec;
15771            measurePath = Environment.getDataAppDirectory(volumeUuid);
15772        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15773            installFlags = INSTALL_EXTERNAL;
15774            moveCompleteApp = false;
15775            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15776        } else {
15777            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15778            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15779                    || !volume.isMountedWritable()) {
15780                unfreezePackage(packageName);
15781                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15782                        "Move location not mounted private volume");
15783            }
15784
15785            Preconditions.checkState(!currentAsec);
15786
15787            installFlags = INSTALL_INTERNAL;
15788            moveCompleteApp = true;
15789            measurePath = Environment.getDataAppDirectory(volumeUuid);
15790        }
15791
15792        final PackageStats stats = new PackageStats(null, -1);
15793        synchronized (mInstaller) {
15794            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15795                unfreezePackage(packageName);
15796                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15797                        "Failed to measure package size");
15798            }
15799        }
15800
15801        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15802                + stats.dataSize);
15803
15804        final long startFreeBytes = measurePath.getFreeSpace();
15805        final long sizeBytes;
15806        if (moveCompleteApp) {
15807            sizeBytes = stats.codeSize + stats.dataSize;
15808        } else {
15809            sizeBytes = stats.codeSize;
15810        }
15811
15812        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15813            unfreezePackage(packageName);
15814            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15815                    "Not enough free space to move");
15816        }
15817
15818        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15819
15820        final CountDownLatch installedLatch = new CountDownLatch(1);
15821        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15822            @Override
15823            public void onUserActionRequired(Intent intent) throws RemoteException {
15824                throw new IllegalStateException();
15825            }
15826
15827            @Override
15828            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15829                    Bundle extras) throws RemoteException {
15830                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15831                        + PackageManager.installStatusToString(returnCode, msg));
15832
15833                installedLatch.countDown();
15834
15835                // Regardless of success or failure of the move operation,
15836                // always unfreeze the package
15837                unfreezePackage(packageName);
15838
15839                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15840                switch (status) {
15841                    case PackageInstaller.STATUS_SUCCESS:
15842                        mMoveCallbacks.notifyStatusChanged(moveId,
15843                                PackageManager.MOVE_SUCCEEDED);
15844                        break;
15845                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15846                        mMoveCallbacks.notifyStatusChanged(moveId,
15847                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15848                        break;
15849                    default:
15850                        mMoveCallbacks.notifyStatusChanged(moveId,
15851                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15852                        break;
15853                }
15854            }
15855        };
15856
15857        final MoveInfo move;
15858        if (moveCompleteApp) {
15859            // Kick off a thread to report progress estimates
15860            new Thread() {
15861                @Override
15862                public void run() {
15863                    while (true) {
15864                        try {
15865                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15866                                break;
15867                            }
15868                        } catch (InterruptedException ignored) {
15869                        }
15870
15871                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15872                        final int progress = 10 + (int) MathUtils.constrain(
15873                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15874                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15875                    }
15876                }
15877            }.start();
15878
15879            final String dataAppName = codeFile.getName();
15880            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15881                    dataAppName, appId, seinfo);
15882        } else {
15883            move = null;
15884        }
15885
15886        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15887
15888        final Message msg = mHandler.obtainMessage(INIT_COPY);
15889        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15890        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15891                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15892        mHandler.sendMessage(msg);
15893    }
15894
15895    @Override
15896    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15897        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15898
15899        final int realMoveId = mNextMoveId.getAndIncrement();
15900        final Bundle extras = new Bundle();
15901        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15902        mMoveCallbacks.notifyCreated(realMoveId, extras);
15903
15904        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15905            @Override
15906            public void onCreated(int moveId, Bundle extras) {
15907                // Ignored
15908            }
15909
15910            @Override
15911            public void onStatusChanged(int moveId, int status, long estMillis) {
15912                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15913            }
15914        };
15915
15916        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15917        storage.setPrimaryStorageUuid(volumeUuid, callback);
15918        return realMoveId;
15919    }
15920
15921    @Override
15922    public int getMoveStatus(int moveId) {
15923        mContext.enforceCallingOrSelfPermission(
15924                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15925        return mMoveCallbacks.mLastStatus.get(moveId);
15926    }
15927
15928    @Override
15929    public void registerMoveCallback(IPackageMoveObserver callback) {
15930        mContext.enforceCallingOrSelfPermission(
15931                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15932        mMoveCallbacks.register(callback);
15933    }
15934
15935    @Override
15936    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15937        mContext.enforceCallingOrSelfPermission(
15938                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15939        mMoveCallbacks.unregister(callback);
15940    }
15941
15942    @Override
15943    public boolean setInstallLocation(int loc) {
15944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15945                null);
15946        if (getInstallLocation() == loc) {
15947            return true;
15948        }
15949        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15950                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15951            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15952                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15953            return true;
15954        }
15955        return false;
15956   }
15957
15958    @Override
15959    public int getInstallLocation() {
15960        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15961                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15962                PackageHelper.APP_INSTALL_AUTO);
15963    }
15964
15965    /** Called by UserManagerService */
15966    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15967        mDirtyUsers.remove(userHandle);
15968        mSettings.removeUserLPw(userHandle);
15969        mPendingBroadcasts.remove(userHandle);
15970        if (mInstaller != null) {
15971            // Technically, we shouldn't be doing this with the package lock
15972            // held.  However, this is very rare, and there is already so much
15973            // other disk I/O going on, that we'll let it slide for now.
15974            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15975            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15976                final String volumeUuid = vol.getFsUuid();
15977                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15978                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15979            }
15980        }
15981        mUserNeedsBadging.delete(userHandle);
15982        removeUnusedPackagesLILPw(userManager, userHandle);
15983    }
15984
15985    /**
15986     * We're removing userHandle and would like to remove any downloaded packages
15987     * that are no longer in use by any other user.
15988     * @param userHandle the user being removed
15989     */
15990    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15991        final boolean DEBUG_CLEAN_APKS = false;
15992        int [] users = userManager.getUserIdsLPr();
15993        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15994        while (psit.hasNext()) {
15995            PackageSetting ps = psit.next();
15996            if (ps.pkg == null) {
15997                continue;
15998            }
15999            final String packageName = ps.pkg.packageName;
16000            // Skip over if system app
16001            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16002                continue;
16003            }
16004            if (DEBUG_CLEAN_APKS) {
16005                Slog.i(TAG, "Checking package " + packageName);
16006            }
16007            boolean keep = false;
16008            for (int i = 0; i < users.length; i++) {
16009                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16010                    keep = true;
16011                    if (DEBUG_CLEAN_APKS) {
16012                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16013                                + users[i]);
16014                    }
16015                    break;
16016                }
16017            }
16018            if (!keep) {
16019                if (DEBUG_CLEAN_APKS) {
16020                    Slog.i(TAG, "  Removing package " + packageName);
16021                }
16022                mHandler.post(new Runnable() {
16023                    public void run() {
16024                        deletePackageX(packageName, userHandle, 0);
16025                    } //end run
16026                });
16027            }
16028        }
16029    }
16030
16031    /** Called by UserManagerService */
16032    void createNewUserLILPw(int userHandle) {
16033        if (mInstaller != null) {
16034            mInstaller.createUserConfig(userHandle);
16035            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16036            applyFactoryDefaultBrowserLPw(userHandle);
16037            primeDomainVerificationsLPw(userHandle);
16038        }
16039    }
16040
16041    void newUserCreated(final int userHandle) {
16042        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16043    }
16044
16045    @Override
16046    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16047        mContext.enforceCallingOrSelfPermission(
16048                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16049                "Only package verification agents can read the verifier device identity");
16050
16051        synchronized (mPackages) {
16052            return mSettings.getVerifierDeviceIdentityLPw();
16053        }
16054    }
16055
16056    @Override
16057    public void setPermissionEnforced(String permission, boolean enforced) {
16058        // TODO: Now that we no longer change GID for storage, this should to away.
16059        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16060                "setPermissionEnforced");
16061        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16062            synchronized (mPackages) {
16063                if (mSettings.mReadExternalStorageEnforced == null
16064                        || mSettings.mReadExternalStorageEnforced != enforced) {
16065                    mSettings.mReadExternalStorageEnforced = enforced;
16066                    mSettings.writeLPr();
16067                }
16068            }
16069            // kill any non-foreground processes so we restart them and
16070            // grant/revoke the GID.
16071            final IActivityManager am = ActivityManagerNative.getDefault();
16072            if (am != null) {
16073                final long token = Binder.clearCallingIdentity();
16074                try {
16075                    am.killProcessesBelowForeground("setPermissionEnforcement");
16076                } catch (RemoteException e) {
16077                } finally {
16078                    Binder.restoreCallingIdentity(token);
16079                }
16080            }
16081        } else {
16082            throw new IllegalArgumentException("No selective enforcement for " + permission);
16083        }
16084    }
16085
16086    @Override
16087    @Deprecated
16088    public boolean isPermissionEnforced(String permission) {
16089        return true;
16090    }
16091
16092    @Override
16093    public boolean isStorageLow() {
16094        final long token = Binder.clearCallingIdentity();
16095        try {
16096            final DeviceStorageMonitorInternal
16097                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16098            if (dsm != null) {
16099                return dsm.isMemoryLow();
16100            } else {
16101                return false;
16102            }
16103        } finally {
16104            Binder.restoreCallingIdentity(token);
16105        }
16106    }
16107
16108    @Override
16109    public IPackageInstaller getPackageInstaller() {
16110        return mInstallerService;
16111    }
16112
16113    private boolean userNeedsBadging(int userId) {
16114        int index = mUserNeedsBadging.indexOfKey(userId);
16115        if (index < 0) {
16116            final UserInfo userInfo;
16117            final long token = Binder.clearCallingIdentity();
16118            try {
16119                userInfo = sUserManager.getUserInfo(userId);
16120            } finally {
16121                Binder.restoreCallingIdentity(token);
16122            }
16123            final boolean b;
16124            if (userInfo != null && userInfo.isManagedProfile()) {
16125                b = true;
16126            } else {
16127                b = false;
16128            }
16129            mUserNeedsBadging.put(userId, b);
16130            return b;
16131        }
16132        return mUserNeedsBadging.valueAt(index);
16133    }
16134
16135    @Override
16136    public KeySet getKeySetByAlias(String packageName, String alias) {
16137        if (packageName == null || alias == null) {
16138            return null;
16139        }
16140        synchronized(mPackages) {
16141            final PackageParser.Package pkg = mPackages.get(packageName);
16142            if (pkg == null) {
16143                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16144                throw new IllegalArgumentException("Unknown package: " + packageName);
16145            }
16146            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16147            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16148        }
16149    }
16150
16151    @Override
16152    public KeySet getSigningKeySet(String packageName) {
16153        if (packageName == null) {
16154            return null;
16155        }
16156        synchronized(mPackages) {
16157            final PackageParser.Package pkg = mPackages.get(packageName);
16158            if (pkg == null) {
16159                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16160                throw new IllegalArgumentException("Unknown package: " + packageName);
16161            }
16162            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16163                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16164                throw new SecurityException("May not access signing KeySet of other apps.");
16165            }
16166            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16167            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16168        }
16169    }
16170
16171    @Override
16172    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16173        if (packageName == null || ks == null) {
16174            return false;
16175        }
16176        synchronized(mPackages) {
16177            final PackageParser.Package pkg = mPackages.get(packageName);
16178            if (pkg == null) {
16179                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16180                throw new IllegalArgumentException("Unknown package: " + packageName);
16181            }
16182            IBinder ksh = ks.getToken();
16183            if (ksh instanceof KeySetHandle) {
16184                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16185                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16186            }
16187            return false;
16188        }
16189    }
16190
16191    @Override
16192    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16193        if (packageName == null || ks == null) {
16194            return false;
16195        }
16196        synchronized(mPackages) {
16197            final PackageParser.Package pkg = mPackages.get(packageName);
16198            if (pkg == null) {
16199                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16200                throw new IllegalArgumentException("Unknown package: " + packageName);
16201            }
16202            IBinder ksh = ks.getToken();
16203            if (ksh instanceof KeySetHandle) {
16204                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16205                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16206            }
16207            return false;
16208        }
16209    }
16210
16211    public void getUsageStatsIfNoPackageUsageInfo() {
16212        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16213            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16214            if (usm == null) {
16215                throw new IllegalStateException("UsageStatsManager must be initialized");
16216            }
16217            long now = System.currentTimeMillis();
16218            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16219            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16220                String packageName = entry.getKey();
16221                PackageParser.Package pkg = mPackages.get(packageName);
16222                if (pkg == null) {
16223                    continue;
16224                }
16225                UsageStats usage = entry.getValue();
16226                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16227                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16228            }
16229        }
16230    }
16231
16232    /**
16233     * Check and throw if the given before/after packages would be considered a
16234     * downgrade.
16235     */
16236    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16237            throws PackageManagerException {
16238        if (after.versionCode < before.mVersionCode) {
16239            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16240                    "Update version code " + after.versionCode + " is older than current "
16241                    + before.mVersionCode);
16242        } else if (after.versionCode == before.mVersionCode) {
16243            if (after.baseRevisionCode < before.baseRevisionCode) {
16244                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16245                        "Update base revision code " + after.baseRevisionCode
16246                        + " is older than current " + before.baseRevisionCode);
16247            }
16248
16249            if (!ArrayUtils.isEmpty(after.splitNames)) {
16250                for (int i = 0; i < after.splitNames.length; i++) {
16251                    final String splitName = after.splitNames[i];
16252                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16253                    if (j != -1) {
16254                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16255                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16256                                    "Update split " + splitName + " revision code "
16257                                    + after.splitRevisionCodes[i] + " is older than current "
16258                                    + before.splitRevisionCodes[j]);
16259                        }
16260                    }
16261                }
16262            }
16263        }
16264    }
16265
16266    private static class MoveCallbacks extends Handler {
16267        private static final int MSG_CREATED = 1;
16268        private static final int MSG_STATUS_CHANGED = 2;
16269
16270        private final RemoteCallbackList<IPackageMoveObserver>
16271                mCallbacks = new RemoteCallbackList<>();
16272
16273        private final SparseIntArray mLastStatus = new SparseIntArray();
16274
16275        public MoveCallbacks(Looper looper) {
16276            super(looper);
16277        }
16278
16279        public void register(IPackageMoveObserver callback) {
16280            mCallbacks.register(callback);
16281        }
16282
16283        public void unregister(IPackageMoveObserver callback) {
16284            mCallbacks.unregister(callback);
16285        }
16286
16287        @Override
16288        public void handleMessage(Message msg) {
16289            final SomeArgs args = (SomeArgs) msg.obj;
16290            final int n = mCallbacks.beginBroadcast();
16291            for (int i = 0; i < n; i++) {
16292                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16293                try {
16294                    invokeCallback(callback, msg.what, args);
16295                } catch (RemoteException ignored) {
16296                }
16297            }
16298            mCallbacks.finishBroadcast();
16299            args.recycle();
16300        }
16301
16302        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16303                throws RemoteException {
16304            switch (what) {
16305                case MSG_CREATED: {
16306                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16307                    break;
16308                }
16309                case MSG_STATUS_CHANGED: {
16310                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16311                    break;
16312                }
16313            }
16314        }
16315
16316        private void notifyCreated(int moveId, Bundle extras) {
16317            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16318
16319            final SomeArgs args = SomeArgs.obtain();
16320            args.argi1 = moveId;
16321            args.arg2 = extras;
16322            obtainMessage(MSG_CREATED, args).sendToTarget();
16323        }
16324
16325        private void notifyStatusChanged(int moveId, int status) {
16326            notifyStatusChanged(moveId, status, -1);
16327        }
16328
16329        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16330            Slog.v(TAG, "Move " + moveId + " status " + status);
16331
16332            final SomeArgs args = SomeArgs.obtain();
16333            args.argi1 = moveId;
16334            args.argi2 = status;
16335            args.arg3 = estMillis;
16336            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16337
16338            synchronized (mLastStatus) {
16339                mLastStatus.put(moveId, status);
16340            }
16341        }
16342    }
16343
16344    private final class OnPermissionChangeListeners extends Handler {
16345        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16346
16347        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16348                new RemoteCallbackList<>();
16349
16350        public OnPermissionChangeListeners(Looper looper) {
16351            super(looper);
16352        }
16353
16354        @Override
16355        public void handleMessage(Message msg) {
16356            switch (msg.what) {
16357                case MSG_ON_PERMISSIONS_CHANGED: {
16358                    final int uid = msg.arg1;
16359                    handleOnPermissionsChanged(uid);
16360                } break;
16361            }
16362        }
16363
16364        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16365            mPermissionListeners.register(listener);
16366
16367        }
16368
16369        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16370            mPermissionListeners.unregister(listener);
16371        }
16372
16373        public void onPermissionsChanged(int uid) {
16374            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16375                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16376            }
16377        }
16378
16379        private void handleOnPermissionsChanged(int uid) {
16380            final int count = mPermissionListeners.beginBroadcast();
16381            try {
16382                for (int i = 0; i < count; i++) {
16383                    IOnPermissionsChangeListener callback = mPermissionListeners
16384                            .getBroadcastItem(i);
16385                    try {
16386                        callback.onPermissionsChanged(uid);
16387                    } catch (RemoteException e) {
16388                        Log.e(TAG, "Permission listener is dead", e);
16389                    }
16390                }
16391            } finally {
16392                mPermissionListeners.finishBroadcast();
16393            }
16394        }
16395    }
16396
16397    private class PackageManagerInternalImpl extends PackageManagerInternal {
16398        @Override
16399        public void setLocationPackagesProvider(PackagesProvider provider) {
16400            synchronized (mPackages) {
16401                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16402            }
16403        }
16404
16405        @Override
16406        public void setImePackagesProvider(PackagesProvider provider) {
16407            synchronized (mPackages) {
16408                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16409            }
16410        }
16411
16412        @Override
16413        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16414            synchronized (mPackages) {
16415                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16416            }
16417        }
16418
16419        @Override
16420        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16421            synchronized (mPackages) {
16422                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16423            }
16424        }
16425
16426        @Override
16427        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16428            synchronized (mPackages) {
16429                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16430            }
16431        }
16432
16433        @Override
16434        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16435            synchronized (mPackages) {
16436                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16437            }
16438        }
16439
16440        @Override
16441        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16442            synchronized (mPackages) {
16443                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16444                        packageName, userId);
16445            }
16446        }
16447
16448        @Override
16449        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16450            synchronized (mPackages) {
16451                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16452                        packageName, userId);
16453            }
16454        }
16455    }
16456
16457    @Override
16458    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16459        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16460        synchronized (mPackages) {
16461            final long identity = Binder.clearCallingIdentity();
16462            try {
16463                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16464                        packageNames, userId);
16465            } finally {
16466                Binder.restoreCallingIdentity(identity);
16467            }
16468        }
16469    }
16470
16471    private static void enforceSystemOrPhoneCaller(String tag) {
16472        int callingUid = Binder.getCallingUid();
16473        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16474            throw new SecurityException(
16475                    "Cannot call " + tag + " from UID " + callingUid);
16476        }
16477    }
16478}
16479