PackageManagerService.java revision 6ee871e59812fea4525c50231f677c4bd10c74b8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86import android.Manifest;
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IOnPermissionsChangeListener;
108import android.content.pm.IPackageDataObserver;
109import android.content.pm.IPackageDeleteObserver;
110import android.content.pm.IPackageDeleteObserver2;
111import android.content.pm.IPackageInstallObserver2;
112import android.content.pm.IPackageInstaller;
113import android.content.pm.IPackageManager;
114import android.content.pm.IPackageMoveObserver;
115import android.content.pm.IPackageStatsObserver;
116import android.content.pm.InstrumentationInfo;
117import android.content.pm.IntentFilterVerificationInfo;
118import android.content.pm.KeySet;
119import android.content.pm.ManifestDigest;
120import android.content.pm.PackageCleanItem;
121import android.content.pm.PackageInfo;
122import android.content.pm.PackageInfoLite;
123import android.content.pm.PackageInstaller;
124import android.content.pm.PackageManager;
125import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126import android.content.pm.PackageManagerInternal;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageParser.ActivityIntentInfo;
129import android.content.pm.PackageParser.PackageLite;
130import android.content.pm.PackageParser.PackageParserException;
131import android.content.pm.PackageStats;
132import android.content.pm.PackageUserState;
133import android.content.pm.ParceledListSlice;
134import android.content.pm.PermissionGroupInfo;
135import android.content.pm.PermissionInfo;
136import android.content.pm.ProviderInfo;
137import android.content.pm.ResolveInfo;
138import android.content.pm.ServiceInfo;
139import android.content.pm.Signature;
140import android.content.pm.UserInfo;
141import android.content.pm.VerificationParams;
142import android.content.pm.VerifierDeviceIdentity;
143import android.content.pm.VerifierInfo;
144import android.content.res.Resources;
145import android.hardware.display.DisplayManager;
146import android.net.Uri;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Debug;
151import android.os.Environment;
152import android.os.Environment.UserEnvironment;
153import android.os.FileUtils;
154import android.os.Handler;
155import android.os.IBinder;
156import android.os.Looper;
157import android.os.Message;
158import android.os.Parcel;
159import android.os.ParcelFileDescriptor;
160import android.os.Process;
161import android.os.RemoteCallbackList;
162import android.os.RemoteException;
163import android.os.SELinux;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.storage.IMountService;
170import android.os.storage.MountServiceInternal;
171import android.os.storage.StorageEventListener;
172import android.os.storage.StorageManager;
173import android.os.storage.VolumeInfo;
174import android.os.storage.VolumeRecord;
175import android.security.KeyStore;
176import android.security.SystemKeyStore;
177import android.system.ErrnoException;
178import android.system.Os;
179import android.system.StructStat;
180import android.text.TextUtils;
181import android.text.format.DateUtils;
182import android.util.ArrayMap;
183import android.util.ArraySet;
184import android.util.AtomicFile;
185import android.util.DisplayMetrics;
186import android.util.EventLog;
187import android.util.ExceptionUtils;
188import android.util.Log;
189import android.util.LogPrinter;
190import android.util.MathUtils;
191import android.util.PrintStreamPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
196import android.util.Xml;
197import android.view.Display;
198
199import dalvik.system.DexFile;
200import dalvik.system.VMRuntime;
201
202import libcore.io.IoUtils;
203import libcore.util.EmptyArray;
204
205import com.android.internal.R;
206import com.android.internal.annotations.GuardedBy;
207import com.android.internal.app.IMediaContainerService;
208import com.android.internal.app.ResolverActivity;
209import com.android.internal.content.NativeLibraryHelper;
210import com.android.internal.content.PackageHelper;
211import com.android.internal.os.IParcelFileDescriptorFactory;
212import com.android.internal.os.SomeArgs;
213import com.android.internal.os.Zygote;
214import com.android.internal.util.ArrayUtils;
215import com.android.internal.util.FastPrintWriter;
216import com.android.internal.util.FastXmlSerializer;
217import com.android.internal.util.IndentingPrintWriter;
218import com.android.internal.util.Preconditions;
219import com.android.server.EventLogTags;
220import com.android.server.FgThread;
221import com.android.server.IntentResolver;
222import com.android.server.LocalServices;
223import com.android.server.ServiceThread;
224import com.android.server.SystemConfig;
225import com.android.server.Watchdog;
226import com.android.server.pm.PermissionsState.PermissionState;
227import com.android.server.pm.Settings.DatabaseVersion;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = true;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REQUIRE_KNOWN = 1<<12;
327    static final int SCAN_MOVE = 1<<13;
328    static final int SCAN_INITIAL = 1<<14;
329
330    static final int REMOVE_CHATTY = 1<<16;
331
332    private static final int[] EMPTY_INT_ARRAY = new int[0];
333
334    /**
335     * Timeout (in milliseconds) after which the watchdog should declare that
336     * our handler thread is wedged.  The usual default for such things is one
337     * minute but we sometimes do very lengthy I/O operations on this thread,
338     * such as installing multi-gigabyte applications, so ours needs to be longer.
339     */
340    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
341
342    /**
343     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
344     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
345     * settings entry if available, otherwise we use the hardcoded default.  If it's been
346     * more than this long since the last fstrim, we force one during the boot sequence.
347     *
348     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
349     * one gets run at the next available charging+idle time.  This final mandatory
350     * no-fstrim check kicks in only of the other scheduling criteria is never met.
351     */
352    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
353
354    /**
355     * Whether verification is enabled by default.
356     */
357    private static final boolean DEFAULT_VERIFY_ENABLE = true;
358
359    /**
360     * The default maximum time to wait for the verification agent to return in
361     * milliseconds.
362     */
363    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
364
365    /**
366     * The default response for package verification timeout.
367     *
368     * This can be either PackageManager.VERIFICATION_ALLOW or
369     * PackageManager.VERIFICATION_REJECT.
370     */
371    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
372
373    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
374
375    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
376            DEFAULT_CONTAINER_PACKAGE,
377            "com.android.defcontainer.DefaultContainerService");
378
379    private static final String KILL_APP_REASON_GIDS_CHANGED =
380            "permission grant or revoke changed gids";
381
382    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
383            "permissions revoked";
384
385    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
386
387    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
388
389    /** Permission grant: not grant the permission. */
390    private static final int GRANT_DENIED = 1;
391
392    /** Permission grant: grant the permission as an install permission. */
393    private static final int GRANT_INSTALL = 2;
394
395    /** Permission grant: grant the permission as an install permission for a legacy app. */
396    private static final int GRANT_INSTALL_LEGACY = 3;
397
398    /** Permission grant: grant the permission as a runtime one. */
399    private static final int GRANT_RUNTIME = 4;
400
401    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
402    private static final int GRANT_UPGRADE = 5;
403
404    /** Canonical intent used to identify what counts as a "web browser" app */
405    private static final Intent sBrowserIntent;
406    static {
407        sBrowserIntent = new Intent();
408        sBrowserIntent.setAction(Intent.ACTION_VIEW);
409        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
410        sBrowserIntent.setData(Uri.parse("http:"));
411    }
412
413    final ServiceThread mHandlerThread;
414
415    final PackageHandler mHandler;
416
417    /**
418     * Messages for {@link #mHandler} that need to wait for system ready before
419     * being dispatched.
420     */
421    private ArrayList<Message> mPostSystemReadyMessages;
422
423    final int mSdkVersion = Build.VERSION.SDK_INT;
424
425    final Context mContext;
426    final boolean mFactoryTest;
427    final boolean mOnlyCore;
428    final boolean mLazyDexOpt;
429    final long mDexOptLRUThresholdInMills;
430    final DisplayMetrics mMetrics;
431    final int mDefParseFlags;
432    final String[] mSeparateProcesses;
433    final boolean mIsUpgrade;
434
435    // This is where all application persistent data goes.
436    final File mAppDataDir;
437
438    // This is where all application persistent data goes for secondary users.
439    final File mUserAppDataDir;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451
452    /**
453     * Directory to which applications installed internally have their
454     * 32 bit native libraries copied.
455     */
456    private File mAppLib32InstallDir;
457
458    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
459    // apps.
460    final File mDrmAppPrivateInstallDir;
461
462    // ----------------------------------------------------------------
463
464    // Lock for state used when installing and doing other long running
465    // operations.  Methods that must be called with this lock held have
466    // the suffix "LI".
467    final Object mInstallLock = new Object();
468
469    // ----------------------------------------------------------------
470
471    // Keys are String (package name), values are Package.  This also serves
472    // as the lock for the global state.  Methods that must be called with
473    // this lock held have the prefix "LP".
474    @GuardedBy("mPackages")
475    final ArrayMap<String, PackageParser.Package> mPackages =
476            new ArrayMap<String, PackageParser.Package>();
477
478    // Tracks available target package names -> overlay package paths.
479    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
480        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
481
482    /**
483     * Tracks new system packages [receiving in an OTA] that we expect to
484     * find updated user-installed versions. Keys are package name, values
485     * are package location.
486     */
487    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
488
489    final Settings mSettings;
490    boolean mRestoredSettings;
491
492    // System configuration read by SystemConfig.
493    final int[] mGlobalGids;
494    final SparseArray<ArraySet<String>> mSystemPermissions;
495    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
496
497    // If mac_permissions.xml was found for seinfo labeling.
498    boolean mFoundPolicyFile;
499
500    // If a recursive restorecon of /data/data/<pkg> is needed.
501    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
502
503    public static final class SharedLibraryEntry {
504        public final String path;
505        public final String apk;
506
507        SharedLibraryEntry(String _path, String _apk) {
508            path = _path;
509            apk = _apk;
510        }
511    }
512
513    // Currently known shared libraries.
514    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
515            new ArrayMap<String, SharedLibraryEntry>();
516
517    // All available activities, for your resolving pleasure.
518    final ActivityIntentResolver mActivities =
519            new ActivityIntentResolver();
520
521    // All available receivers, for your resolving pleasure.
522    final ActivityIntentResolver mReceivers =
523            new ActivityIntentResolver();
524
525    // All available services, for your resolving pleasure.
526    final ServiceIntentResolver mServices = new ServiceIntentResolver();
527
528    // All available providers, for your resolving pleasure.
529    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
530
531    // Mapping from provider base names (first directory in content URI codePath)
532    // to the provider information.
533    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
534            new ArrayMap<String, PackageParser.Provider>();
535
536    // Mapping from instrumentation class names to info about them.
537    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
538            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
539
540    // Mapping from permission names to info about them.
541    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
542            new ArrayMap<String, PackageParser.PermissionGroup>();
543
544    // Packages whose data we have transfered into another package, thus
545    // should no longer exist.
546    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
547
548    // Broadcast actions that are only available to the system.
549    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
550
551    /** List of packages waiting for verification. */
552    final SparseArray<PackageVerificationState> mPendingVerification
553            = new SparseArray<PackageVerificationState>();
554
555    /** Set of packages associated with each app op permission. */
556    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
557
558    final PackageInstallerService mInstallerService;
559
560    private final PackageDexOptimizer mPackageDexOptimizer;
561
562    private AtomicInteger mNextMoveId = new AtomicInteger();
563    private final MoveCallbacks mMoveCallbacks;
564
565    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
566
567    // Cache of users who need badging.
568    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
569
570    /** Token for keys in mPendingVerification. */
571    private int mPendingVerificationToken = 0;
572
573    volatile boolean mSystemReady;
574    volatile boolean mSafeMode;
575    volatile boolean mHasSystemUidErrors;
576
577    ApplicationInfo mAndroidApplication;
578    final ActivityInfo mResolveActivity = new ActivityInfo();
579    final ResolveInfo mResolveInfo = new ResolveInfo();
580    ComponentName mResolveComponentName;
581    PackageParser.Package mPlatformPackage;
582    ComponentName mCustomResolverComponentName;
583
584    boolean mResolverReplaced = false;
585
586    private final ComponentName mIntentFilterVerifierComponent;
587    private int mIntentFilterVerificationToken = 0;
588
589    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
590            = new SparseArray<IntentFilterVerificationState>();
591
592    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
593            new DefaultPermissionGrantPolicy(this);
594
595    private static class IFVerificationParams {
596        PackageParser.Package pkg;
597        boolean replacing;
598        int userId;
599        int verifierUid;
600
601        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
602                int _userId, int _verifierUid) {
603            pkg = _pkg;
604            replacing = _replacing;
605            userId = _userId;
606            replacing = _replacing;
607            verifierUid = _verifierUid;
608        }
609    }
610
611    private interface IntentFilterVerifier<T extends IntentFilter> {
612        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
613                                               T filter, String packageName);
614        void startVerifications(int userId);
615        void receiveVerificationResponse(int verificationId);
616    }
617
618    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
619        private Context mContext;
620        private ComponentName mIntentFilterVerifierComponent;
621        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
622
623        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
624            mContext = context;
625            mIntentFilterVerifierComponent = verifierComponent;
626        }
627
628        private String getDefaultScheme() {
629            return IntentFilter.SCHEME_HTTPS;
630        }
631
632        @Override
633        public void startVerifications(int userId) {
634            // Launch verifications requests
635            int count = mCurrentIntentFilterVerifications.size();
636            for (int n=0; n<count; n++) {
637                int verificationId = mCurrentIntentFilterVerifications.get(n);
638                final IntentFilterVerificationState ivs =
639                        mIntentFilterVerificationStates.get(verificationId);
640
641                String packageName = ivs.getPackageName();
642
643                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
644                final int filterCount = filters.size();
645                ArraySet<String> domainsSet = new ArraySet<>();
646                for (int m=0; m<filterCount; m++) {
647                    PackageParser.ActivityIntentInfo filter = filters.get(m);
648                    domainsSet.addAll(filter.getHostsList());
649                }
650                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
651                synchronized (mPackages) {
652                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
653                            packageName, domainsList) != null) {
654                        scheduleWriteSettingsLocked();
655                    }
656                }
657                sendVerificationRequest(userId, verificationId, ivs);
658            }
659            mCurrentIntentFilterVerifications.clear();
660        }
661
662        private void sendVerificationRequest(int userId, int verificationId,
663                IntentFilterVerificationState ivs) {
664
665            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
668                    verificationId);
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
671                    getDefaultScheme());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
674                    ivs.getHostsString());
675            verificationIntent.putExtra(
676                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
677                    ivs.getPackageName());
678            verificationIntent.setComponent(mIntentFilterVerifierComponent);
679            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680
681            UserHandle user = new UserHandle(userId);
682            mContext.sendBroadcastAsUser(verificationIntent, user);
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Sending IntentFilter verification broadcast");
685        }
686
687        public void receiveVerificationResponse(int verificationId) {
688            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
689
690            final boolean verified = ivs.isVerified();
691
692            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
693            final int count = filters.size();
694            if (DEBUG_DOMAIN_VERIFICATION) {
695                Slog.i(TAG, "Received verification response " + verificationId
696                        + " for " + count + " filters, verified=" + verified);
697            }
698            for (int n=0; n<count; n++) {
699                PackageParser.ActivityIntentInfo filter = filters.get(n);
700                filter.setVerified(verified);
701
702                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
703                        + " verified with result:" + verified + " and hosts:"
704                        + ivs.getHostsString());
705            }
706
707            mIntentFilterVerificationStates.remove(verificationId);
708
709            final String packageName = ivs.getPackageName();
710            IntentFilterVerificationInfo ivi = null;
711
712            synchronized (mPackages) {
713                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
714            }
715            if (ivi == null) {
716                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
717                        + verificationId + " packageName:" + packageName);
718                return;
719            }
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Updating IntentFilterVerificationInfo for package " + packageName
722                            +" verificationId:" + verificationId);
723
724            synchronized (mPackages) {
725                if (verified) {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
727                } else {
728                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
729                }
730                scheduleWriteSettingsLocked();
731
732                final int userId = ivs.getUserId();
733                if (userId != UserHandle.USER_ALL) {
734                    final int userStatus =
735                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
736
737                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
738                    boolean needUpdate = false;
739
740                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
741                    // already been set by the User thru the Disambiguation dialog
742                    switch (userStatus) {
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                            } else {
747                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
748                            }
749                            needUpdate = true;
750                            break;
751
752                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
753                            if (verified) {
754                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
755                                needUpdate = true;
756                            }
757                            break;
758
759                        default:
760                            // Nothing to do
761                    }
762
763                    if (needUpdate) {
764                        mSettings.updateIntentFilterVerificationStatusLPw(
765                                packageName, updatedStatus, userId);
766                        scheduleWritePackageRestrictionsLocked(userId);
767                    }
768                }
769            }
770        }
771
772        @Override
773        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
774                    ActivityIntentInfo filter, String packageName) {
775            if (!hasValidDomains(filter)) {
776                return false;
777            }
778            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
779            if (ivs == null) {
780                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
781                        packageName);
782            }
783            if (DEBUG_DOMAIN_VERIFICATION) {
784                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
785            }
786            ivs.addFilter(filter);
787            return true;
788        }
789
790        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
791                int userId, int verificationId, String packageName) {
792            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
793                    verifierUid, userId, packageName);
794            ivs.setPendingState();
795            synchronized (mPackages) {
796                mIntentFilterVerificationStates.append(verificationId, ivs);
797                mCurrentIntentFilterVerifications.add(verificationId);
798            }
799            return ivs;
800        }
801    }
802
803    private static boolean hasValidDomains(ActivityIntentInfo filter) {
804        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
805                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
806        if (!hasHTTPorHTTPS) {
807            return false;
808        }
809        return true;
810    }
811
812    private IntentFilterVerifier mIntentFilterVerifier;
813
814    // Set of pending broadcasts for aggregating enable/disable of components.
815    static class PendingPackageBroadcasts {
816        // for each user id, a map of <package name -> components within that package>
817        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
818
819        public PendingPackageBroadcasts() {
820            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
821        }
822
823        public ArrayList<String> get(int userId, String packageName) {
824            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
825            return packages.get(packageName);
826        }
827
828        public void put(int userId, String packageName, ArrayList<String> components) {
829            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
830            packages.put(packageName, components);
831        }
832
833        public void remove(int userId, String packageName) {
834            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
835            if (packages != null) {
836                packages.remove(packageName);
837            }
838        }
839
840        public void remove(int userId) {
841            mUidMap.remove(userId);
842        }
843
844        public int userIdCount() {
845            return mUidMap.size();
846        }
847
848        public int userIdAt(int n) {
849            return mUidMap.keyAt(n);
850        }
851
852        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
853            return mUidMap.get(userId);
854        }
855
856        public int size() {
857            // total number of pending broadcast entries across all userIds
858            int num = 0;
859            for (int i = 0; i< mUidMap.size(); i++) {
860                num += mUidMap.valueAt(i).size();
861            }
862            return num;
863        }
864
865        public void clear() {
866            mUidMap.clear();
867        }
868
869        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
870            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
871            if (map == null) {
872                map = new ArrayMap<String, ArrayList<String>>();
873                mUidMap.put(userId, map);
874            }
875            return map;
876        }
877    }
878    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
879
880    // Service Connection to remote media container service to copy
881    // package uri's from external media onto secure containers
882    // or internal storage.
883    private IMediaContainerService mContainerService = null;
884
885    static final int SEND_PENDING_BROADCAST = 1;
886    static final int MCS_BOUND = 3;
887    static final int END_COPY = 4;
888    static final int INIT_COPY = 5;
889    static final int MCS_UNBIND = 6;
890    static final int START_CLEANING_PACKAGE = 7;
891    static final int FIND_INSTALL_LOC = 8;
892    static final int POST_INSTALL = 9;
893    static final int MCS_RECONNECT = 10;
894    static final int MCS_GIVE_UP = 11;
895    static final int UPDATED_MEDIA_STATUS = 12;
896    static final int WRITE_SETTINGS = 13;
897    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
898    static final int PACKAGE_VERIFIED = 15;
899    static final int CHECK_PENDING_VERIFICATION = 16;
900    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
901    static final int INTENT_FILTER_VERIFIED = 18;
902
903    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
904
905    // Delay time in millisecs
906    static final int BROADCAST_DELAY = 10 * 1000;
907
908    static UserManagerService sUserManager;
909
910    // Stores a list of users whose package restrictions file needs to be updated
911    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
912
913    final private DefaultContainerConnection mDefContainerConn =
914            new DefaultContainerConnection();
915    class DefaultContainerConnection implements ServiceConnection {
916        public void onServiceConnected(ComponentName name, IBinder service) {
917            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
918            IMediaContainerService imcs =
919                IMediaContainerService.Stub.asInterface(service);
920            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
921        }
922
923        public void onServiceDisconnected(ComponentName name) {
924            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
925        }
926    }
927
928    // Recordkeeping of restore-after-install operations that are currently in flight
929    // between the Package Manager and the Backup Manager
930    class PostInstallData {
931        public InstallArgs args;
932        public PackageInstalledInfo res;
933
934        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
935            args = _a;
936            res = _r;
937        }
938    }
939
940    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
941    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
942
943    // XML tags for backup/restore of various bits of state
944    private static final String TAG_PREFERRED_BACKUP = "pa";
945    private static final String TAG_DEFAULT_APPS = "da";
946    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
947
948    final String mRequiredVerifierPackage;
949    final String mRequiredInstallerPackage;
950
951    private final PackageUsage mPackageUsage = new PackageUsage();
952
953    private class PackageUsage {
954        private static final int WRITE_INTERVAL
955            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
956
957        private final Object mFileLock = new Object();
958        private final AtomicLong mLastWritten = new AtomicLong(0);
959        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
960
961        private boolean mIsHistoricalPackageUsageAvailable = true;
962
963        boolean isHistoricalPackageUsageAvailable() {
964            return mIsHistoricalPackageUsageAvailable;
965        }
966
967        void write(boolean force) {
968            if (force) {
969                writeInternal();
970                return;
971            }
972            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
973                && !DEBUG_DEXOPT) {
974                return;
975            }
976            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
977                new Thread("PackageUsage_DiskWriter") {
978                    @Override
979                    public void run() {
980                        try {
981                            writeInternal();
982                        } finally {
983                            mBackgroundWriteRunning.set(false);
984                        }
985                    }
986                }.start();
987            }
988        }
989
990        private void writeInternal() {
991            synchronized (mPackages) {
992                synchronized (mFileLock) {
993                    AtomicFile file = getFile();
994                    FileOutputStream f = null;
995                    try {
996                        f = file.startWrite();
997                        BufferedOutputStream out = new BufferedOutputStream(f);
998                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
999                        StringBuilder sb = new StringBuilder();
1000                        for (PackageParser.Package pkg : mPackages.values()) {
1001                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1002                                continue;
1003                            }
1004                            sb.setLength(0);
1005                            sb.append(pkg.packageName);
1006                            sb.append(' ');
1007                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1008                            sb.append('\n');
1009                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1010                        }
1011                        out.flush();
1012                        file.finishWrite(f);
1013                    } catch (IOException e) {
1014                        if (f != null) {
1015                            file.failWrite(f);
1016                        }
1017                        Log.e(TAG, "Failed to write package usage times", e);
1018                    }
1019                }
1020            }
1021            mLastWritten.set(SystemClock.elapsedRealtime());
1022        }
1023
1024        void readLP() {
1025            synchronized (mFileLock) {
1026                AtomicFile file = getFile();
1027                BufferedInputStream in = null;
1028                try {
1029                    in = new BufferedInputStream(file.openRead());
1030                    StringBuffer sb = new StringBuffer();
1031                    while (true) {
1032                        String packageName = readToken(in, sb, ' ');
1033                        if (packageName == null) {
1034                            break;
1035                        }
1036                        String timeInMillisString = readToken(in, sb, '\n');
1037                        if (timeInMillisString == null) {
1038                            throw new IOException("Failed to find last usage time for package "
1039                                                  + packageName);
1040                        }
1041                        PackageParser.Package pkg = mPackages.get(packageName);
1042                        if (pkg == null) {
1043                            continue;
1044                        }
1045                        long timeInMillis;
1046                        try {
1047                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1048                        } catch (NumberFormatException e) {
1049                            throw new IOException("Failed to parse " + timeInMillisString
1050                                                  + " as a long.", e);
1051                        }
1052                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1053                    }
1054                } catch (FileNotFoundException expected) {
1055                    mIsHistoricalPackageUsageAvailable = false;
1056                } catch (IOException e) {
1057                    Log.w(TAG, "Failed to read package usage times", e);
1058                } finally {
1059                    IoUtils.closeQuietly(in);
1060                }
1061            }
1062            mLastWritten.set(SystemClock.elapsedRealtime());
1063        }
1064
1065        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1066                throws IOException {
1067            sb.setLength(0);
1068            while (true) {
1069                int ch = in.read();
1070                if (ch == -1) {
1071                    if (sb.length() == 0) {
1072                        return null;
1073                    }
1074                    throw new IOException("Unexpected EOF");
1075                }
1076                if (ch == endOfToken) {
1077                    return sb.toString();
1078                }
1079                sb.append((char)ch);
1080            }
1081        }
1082
1083        private AtomicFile getFile() {
1084            File dataDir = Environment.getDataDirectory();
1085            File systemDir = new File(dataDir, "system");
1086            File fname = new File(systemDir, "package-usage.list");
1087            return new AtomicFile(fname);
1088        }
1089    }
1090
1091    class PackageHandler extends Handler {
1092        private boolean mBound = false;
1093        final ArrayList<HandlerParams> mPendingInstalls =
1094            new ArrayList<HandlerParams>();
1095
1096        private boolean connectToService() {
1097            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1098                    " DefaultContainerService");
1099            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1100            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1101            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1102                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1103                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1104                mBound = true;
1105                return true;
1106            }
1107            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108            return false;
1109        }
1110
1111        private void disconnectService() {
1112            mContainerService = null;
1113            mBound = false;
1114            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115            mContext.unbindService(mDefContainerConn);
1116            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117        }
1118
1119        PackageHandler(Looper looper) {
1120            super(looper);
1121        }
1122
1123        public void handleMessage(Message msg) {
1124            try {
1125                doHandleMessage(msg);
1126            } finally {
1127                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1128            }
1129        }
1130
1131        void doHandleMessage(Message msg) {
1132            switch (msg.what) {
1133                case INIT_COPY: {
1134                    HandlerParams params = (HandlerParams) msg.obj;
1135                    int idx = mPendingInstalls.size();
1136                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1137                    // If a bind was already initiated we dont really
1138                    // need to do anything. The pending install
1139                    // will be processed later on.
1140                    if (!mBound) {
1141                        // If this is the only one pending we might
1142                        // have to bind to the service again.
1143                        if (!connectToService()) {
1144                            Slog.e(TAG, "Failed to bind to media container service");
1145                            params.serviceError();
1146                            return;
1147                        } else {
1148                            // Once we bind to the service, the first
1149                            // pending request will be processed.
1150                            mPendingInstalls.add(idx, params);
1151                        }
1152                    } else {
1153                        mPendingInstalls.add(idx, params);
1154                        // Already bound to the service. Just make
1155                        // sure we trigger off processing the first request.
1156                        if (idx == 0) {
1157                            mHandler.sendEmptyMessage(MCS_BOUND);
1158                        }
1159                    }
1160                    break;
1161                }
1162                case MCS_BOUND: {
1163                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1164                    if (msg.obj != null) {
1165                        mContainerService = (IMediaContainerService) msg.obj;
1166                    }
1167                    if (mContainerService == null) {
1168                        if (!mBound) {
1169                            // Something seriously wrong since we are not bound and we are not
1170                            // waiting for connection. Bail out.
1171                            Slog.e(TAG, "Cannot bind to media container service");
1172                            for (HandlerParams params : mPendingInstalls) {
1173                                // Indicate service bind error
1174                                params.serviceError();
1175                            }
1176                            mPendingInstalls.clear();
1177                        } else {
1178                            Slog.w(TAG, "Waiting to connect to media container service");
1179                        }
1180                    } else if (mPendingInstalls.size() > 0) {
1181                        HandlerParams params = mPendingInstalls.get(0);
1182                        if (params != null) {
1183                            if (params.startCopy()) {
1184                                // We are done...  look for more work or to
1185                                // go idle.
1186                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1187                                        "Checking for more work or unbind...");
1188                                // Delete pending install
1189                                if (mPendingInstalls.size() > 0) {
1190                                    mPendingInstalls.remove(0);
1191                                }
1192                                if (mPendingInstalls.size() == 0) {
1193                                    if (mBound) {
1194                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1195                                                "Posting delayed MCS_UNBIND");
1196                                        removeMessages(MCS_UNBIND);
1197                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1198                                        // Unbind after a little delay, to avoid
1199                                        // continual thrashing.
1200                                        sendMessageDelayed(ubmsg, 10000);
1201                                    }
1202                                } else {
1203                                    // There are more pending requests in queue.
1204                                    // Just post MCS_BOUND message to trigger processing
1205                                    // of next pending install.
1206                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1207                                            "Posting MCS_BOUND for next work");
1208                                    mHandler.sendEmptyMessage(MCS_BOUND);
1209                                }
1210                            }
1211                        }
1212                    } else {
1213                        // Should never happen ideally.
1214                        Slog.w(TAG, "Empty queue");
1215                    }
1216                    break;
1217                }
1218                case MCS_RECONNECT: {
1219                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1220                    if (mPendingInstalls.size() > 0) {
1221                        if (mBound) {
1222                            disconnectService();
1223                        }
1224                        if (!connectToService()) {
1225                            Slog.e(TAG, "Failed to bind to media container service");
1226                            for (HandlerParams params : mPendingInstalls) {
1227                                // Indicate service bind error
1228                                params.serviceError();
1229                            }
1230                            mPendingInstalls.clear();
1231                        }
1232                    }
1233                    break;
1234                }
1235                case MCS_UNBIND: {
1236                    // If there is no actual work left, then time to unbind.
1237                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1238
1239                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1240                        if (mBound) {
1241                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1242
1243                            disconnectService();
1244                        }
1245                    } else if (mPendingInstalls.size() > 0) {
1246                        // There are more pending requests in queue.
1247                        // Just post MCS_BOUND message to trigger processing
1248                        // of next pending install.
1249                        mHandler.sendEmptyMessage(MCS_BOUND);
1250                    }
1251
1252                    break;
1253                }
1254                case MCS_GIVE_UP: {
1255                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1256                    mPendingInstalls.remove(0);
1257                    break;
1258                }
1259                case SEND_PENDING_BROADCAST: {
1260                    String packages[];
1261                    ArrayList<String> components[];
1262                    int size = 0;
1263                    int uids[];
1264                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1265                    synchronized (mPackages) {
1266                        if (mPendingBroadcasts == null) {
1267                            return;
1268                        }
1269                        size = mPendingBroadcasts.size();
1270                        if (size <= 0) {
1271                            // Nothing to be done. Just return
1272                            return;
1273                        }
1274                        packages = new String[size];
1275                        components = new ArrayList[size];
1276                        uids = new int[size];
1277                        int i = 0;  // filling out the above arrays
1278
1279                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1280                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1281                            Iterator<Map.Entry<String, ArrayList<String>>> it
1282                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1283                                            .entrySet().iterator();
1284                            while (it.hasNext() && i < size) {
1285                                Map.Entry<String, ArrayList<String>> ent = it.next();
1286                                packages[i] = ent.getKey();
1287                                components[i] = ent.getValue();
1288                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1289                                uids[i] = (ps != null)
1290                                        ? UserHandle.getUid(packageUserId, ps.appId)
1291                                        : -1;
1292                                i++;
1293                            }
1294                        }
1295                        size = i;
1296                        mPendingBroadcasts.clear();
1297                    }
1298                    // Send broadcasts
1299                    for (int i = 0; i < size; i++) {
1300                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1301                    }
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1303                    break;
1304                }
1305                case START_CLEANING_PACKAGE: {
1306                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1307                    final String packageName = (String)msg.obj;
1308                    final int userId = msg.arg1;
1309                    final boolean andCode = msg.arg2 != 0;
1310                    synchronized (mPackages) {
1311                        if (userId == UserHandle.USER_ALL) {
1312                            int[] users = sUserManager.getUserIds();
1313                            for (int user : users) {
1314                                mSettings.addPackageToCleanLPw(
1315                                        new PackageCleanItem(user, packageName, andCode));
1316                            }
1317                        } else {
1318                            mSettings.addPackageToCleanLPw(
1319                                    new PackageCleanItem(userId, packageName, andCode));
1320                        }
1321                    }
1322                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1323                    startCleaningPackages();
1324                } break;
1325                case POST_INSTALL: {
1326                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1327                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1328                    mRunningInstalls.delete(msg.arg1);
1329                    boolean deleteOld = false;
1330
1331                    if (data != null) {
1332                        InstallArgs args = data.args;
1333                        PackageInstalledInfo res = data.res;
1334
1335                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1336                            final String packageName = res.pkg.applicationInfo.packageName;
1337                            res.removedInfo.sendBroadcast(false, true, false);
1338                            Bundle extras = new Bundle(1);
1339                            extras.putInt(Intent.EXTRA_UID, res.uid);
1340
1341                            // Now that we successfully installed the package, grant runtime
1342                            // permissions if requested before broadcasting the install.
1343                            if ((args.installFlags
1344                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1345                                grantRequestedRuntimePermissions(res.pkg,
1346                                        args.user.getIdentifier());
1347                            }
1348
1349                            // Determine the set of users who are adding this
1350                            // package for the first time vs. those who are seeing
1351                            // an update.
1352                            int[] firstUsers;
1353                            int[] updateUsers = new int[0];
1354                            if (res.origUsers == null || res.origUsers.length == 0) {
1355                                firstUsers = res.newUsers;
1356                            } else {
1357                                firstUsers = new int[0];
1358                                for (int i=0; i<res.newUsers.length; i++) {
1359                                    int user = res.newUsers[i];
1360                                    boolean isNew = true;
1361                                    for (int j=0; j<res.origUsers.length; j++) {
1362                                        if (res.origUsers[j] == user) {
1363                                            isNew = false;
1364                                            break;
1365                                        }
1366                                    }
1367                                    if (isNew) {
1368                                        int[] newFirst = new int[firstUsers.length+1];
1369                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1370                                                firstUsers.length);
1371                                        newFirst[firstUsers.length] = user;
1372                                        firstUsers = newFirst;
1373                                    } else {
1374                                        int[] newUpdate = new int[updateUsers.length+1];
1375                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1376                                                updateUsers.length);
1377                                        newUpdate[updateUsers.length] = user;
1378                                        updateUsers = newUpdate;
1379                                    }
1380                                }
1381                            }
1382                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1383                                    packageName, extras, null, null, firstUsers);
1384                            final boolean update = res.removedInfo.removedPackage != null;
1385                            if (update) {
1386                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1387                            }
1388                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1389                                    packageName, extras, null, null, updateUsers);
1390                            if (update) {
1391                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1392                                        packageName, extras, null, null, updateUsers);
1393                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1394                                        null, null, packageName, null, updateUsers);
1395
1396                                // treat asec-hosted packages like removable media on upgrade
1397                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1398                                    if (DEBUG_INSTALL) {
1399                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1400                                                + " is ASEC-hosted -> AVAILABLE");
1401                                    }
1402                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1403                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1404                                    pkgList.add(packageName);
1405                                    sendResourcesChangedBroadcast(true, true,
1406                                            pkgList,uidArray, null);
1407                                }
1408                            }
1409                            if (res.removedInfo.args != null) {
1410                                // Remove the replaced package's older resources safely now
1411                                deleteOld = true;
1412                            }
1413
1414                            // If this app is a browser and it's newly-installed for some
1415                            // users, clear any default-browser state in those users
1416                            if (firstUsers.length > 0) {
1417                                // the app's nature doesn't depend on the user, so we can just
1418                                // check its browser nature in any user and generalize.
1419                                if (packageIsBrowser(packageName, firstUsers[0])) {
1420                                    synchronized (mPackages) {
1421                                        for (int userId : firstUsers) {
1422                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1423                                        }
1424                                    }
1425                                }
1426                            }
1427                            // Log current value of "unknown sources" setting
1428                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1429                                getUnknownSourcesSettings());
1430                        }
1431                        // Force a gc to clear up things
1432                        Runtime.getRuntime().gc();
1433                        // We delete after a gc for applications  on sdcard.
1434                        if (deleteOld) {
1435                            synchronized (mInstallLock) {
1436                                res.removedInfo.args.doPostDeleteLI(true);
1437                            }
1438                        }
1439                        if (args.observer != null) {
1440                            try {
1441                                Bundle extras = extrasForInstallResult(res);
1442                                args.observer.onPackageInstalled(res.name, res.returnCode,
1443                                        res.returnMsg, extras);
1444                            } catch (RemoteException e) {
1445                                Slog.i(TAG, "Observer no longer exists.");
1446                            }
1447                        }
1448                    } else {
1449                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1450                    }
1451                } break;
1452                case UPDATED_MEDIA_STATUS: {
1453                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1454                    boolean reportStatus = msg.arg1 == 1;
1455                    boolean doGc = msg.arg2 == 1;
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1457                    if (doGc) {
1458                        // Force a gc to clear up stale containers.
1459                        Runtime.getRuntime().gc();
1460                    }
1461                    if (msg.obj != null) {
1462                        @SuppressWarnings("unchecked")
1463                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1464                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1465                        // Unload containers
1466                        unloadAllContainers(args);
1467                    }
1468                    if (reportStatus) {
1469                        try {
1470                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1471                            PackageHelper.getMountService().finishMediaUpdate();
1472                        } catch (RemoteException e) {
1473                            Log.e(TAG, "MountService not running?");
1474                        }
1475                    }
1476                } break;
1477                case WRITE_SETTINGS: {
1478                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1479                    synchronized (mPackages) {
1480                        removeMessages(WRITE_SETTINGS);
1481                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1482                        mSettings.writeLPr();
1483                        mDirtyUsers.clear();
1484                    }
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486                } break;
1487                case WRITE_PACKAGE_RESTRICTIONS: {
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1489                    synchronized (mPackages) {
1490                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1491                        for (int userId : mDirtyUsers) {
1492                            mSettings.writePackageRestrictionsLPr(userId);
1493                        }
1494                        mDirtyUsers.clear();
1495                    }
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1497                } break;
1498                case CHECK_PENDING_VERIFICATION: {
1499                    final int verificationId = msg.arg1;
1500                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1501
1502                    if ((state != null) && !state.timeoutExtended()) {
1503                        final InstallArgs args = state.getInstallArgs();
1504                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1505
1506                        Slog.i(TAG, "Verification timed out for " + originUri);
1507                        mPendingVerification.remove(verificationId);
1508
1509                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1510
1511                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1512                            Slog.i(TAG, "Continuing with installation of " + originUri);
1513                            state.setVerifierResponse(Binder.getCallingUid(),
1514                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1515                            broadcastPackageVerified(verificationId, originUri,
1516                                    PackageManager.VERIFICATION_ALLOW,
1517                                    state.getInstallArgs().getUser());
1518                            try {
1519                                ret = args.copyApk(mContainerService, true);
1520                            } catch (RemoteException e) {
1521                                Slog.e(TAG, "Could not contact the ContainerService");
1522                            }
1523                        } else {
1524                            broadcastPackageVerified(verificationId, originUri,
1525                                    PackageManager.VERIFICATION_REJECT,
1526                                    state.getInstallArgs().getUser());
1527                        }
1528
1529                        processPendingInstall(args, ret);
1530                        mHandler.sendEmptyMessage(MCS_UNBIND);
1531                    }
1532                    break;
1533                }
1534                case PACKAGE_VERIFIED: {
1535                    final int verificationId = msg.arg1;
1536
1537                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1538                    if (state == null) {
1539                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1540                        break;
1541                    }
1542
1543                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1544
1545                    state.setVerifierResponse(response.callerUid, response.code);
1546
1547                    if (state.isVerificationComplete()) {
1548                        mPendingVerification.remove(verificationId);
1549
1550                        final InstallArgs args = state.getInstallArgs();
1551                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1552
1553                        int ret;
1554                        if (state.isInstallAllowed()) {
1555                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1556                            broadcastPackageVerified(verificationId, originUri,
1557                                    response.code, state.getInstallArgs().getUser());
1558                            try {
1559                                ret = args.copyApk(mContainerService, true);
1560                            } catch (RemoteException e) {
1561                                Slog.e(TAG, "Could not contact the ContainerService");
1562                            }
1563                        } else {
1564                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1565                        }
1566
1567                        processPendingInstall(args, ret);
1568
1569                        mHandler.sendEmptyMessage(MCS_UNBIND);
1570                    }
1571
1572                    break;
1573                }
1574                case START_INTENT_FILTER_VERIFICATIONS: {
1575                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1576                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1577                            params.replacing, params.pkg);
1578                    break;
1579                }
1580                case INTENT_FILTER_VERIFIED: {
1581                    final int verificationId = msg.arg1;
1582
1583                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1584                            verificationId);
1585                    if (state == null) {
1586                        Slog.w(TAG, "Invalid IntentFilter verification token "
1587                                + verificationId + " received");
1588                        break;
1589                    }
1590
1591                    final int userId = state.getUserId();
1592
1593                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1594                            "Processing IntentFilter verification with token:"
1595                            + verificationId + " and userId:" + userId);
1596
1597                    final IntentFilterVerificationResponse response =
1598                            (IntentFilterVerificationResponse) msg.obj;
1599
1600                    state.setVerifierResponse(response.callerUid, response.code);
1601
1602                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1603                            "IntentFilter verification with token:" + verificationId
1604                            + " and userId:" + userId
1605                            + " is settings verifier response with response code:"
1606                            + response.code);
1607
1608                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1609                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1610                                + response.getFailedDomainsString());
1611                    }
1612
1613                    if (state.isVerificationComplete()) {
1614                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1615                    } else {
1616                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1617                                "IntentFilter verification with token:" + verificationId
1618                                + " was not said to be complete");
1619                    }
1620
1621                    break;
1622                }
1623            }
1624        }
1625    }
1626
1627    private StorageEventListener mStorageListener = new StorageEventListener() {
1628        @Override
1629        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1630            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1631                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1632                    final String volumeUuid = vol.getFsUuid();
1633
1634                    // Clean up any users or apps that were removed or recreated
1635                    // while this volume was missing
1636                    reconcileUsers(volumeUuid);
1637                    reconcileApps(volumeUuid);
1638
1639                    // Clean up any install sessions that expired or were
1640                    // cancelled while this volume was missing
1641                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1642
1643                    loadPrivatePackages(vol);
1644
1645                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1646                    unloadPrivatePackages(vol);
1647                }
1648            }
1649
1650            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1651                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1652                    updateExternalMediaStatus(true, false);
1653                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1654                    updateExternalMediaStatus(false, false);
1655                }
1656            }
1657        }
1658
1659        @Override
1660        public void onVolumeForgotten(String fsUuid) {
1661            // Remove any apps installed on the forgotten volume
1662            synchronized (mPackages) {
1663                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1664                for (PackageSetting ps : packages) {
1665                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1666                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1667                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1668                }
1669
1670                mSettings.writeLPr();
1671            }
1672        }
1673    };
1674
1675    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1676        if (userId >= UserHandle.USER_OWNER) {
1677            grantRequestedRuntimePermissionsForUser(pkg, userId);
1678        } else if (userId == UserHandle.USER_ALL) {
1679            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1680                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1681            }
1682        }
1683
1684        // We could have touched GID membership, so flush out packages.list
1685        synchronized (mPackages) {
1686            mSettings.writePackageListLPr();
1687        }
1688    }
1689
1690    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1691        SettingBase sb = (SettingBase) pkg.mExtras;
1692        if (sb == null) {
1693            return;
1694        }
1695
1696        PermissionsState permissionsState = sb.getPermissionsState();
1697
1698        for (String permission : pkg.requestedPermissions) {
1699            BasePermission bp = mSettings.mPermissions.get(permission);
1700            if (bp != null && bp.isRuntime()) {
1701                permissionsState.grantRuntimePermission(bp, userId);
1702            }
1703        }
1704    }
1705
1706    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1707        Bundle extras = null;
1708        switch (res.returnCode) {
1709            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1710                extras = new Bundle();
1711                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1712                        res.origPermission);
1713                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1714                        res.origPackage);
1715                break;
1716            }
1717            case PackageManager.INSTALL_SUCCEEDED: {
1718                extras = new Bundle();
1719                extras.putBoolean(Intent.EXTRA_REPLACING,
1720                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1721                break;
1722            }
1723        }
1724        return extras;
1725    }
1726
1727    void scheduleWriteSettingsLocked() {
1728        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1729            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1730        }
1731    }
1732
1733    void scheduleWritePackageRestrictionsLocked(int userId) {
1734        if (!sUserManager.exists(userId)) return;
1735        mDirtyUsers.add(userId);
1736        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1737            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1738        }
1739    }
1740
1741    public static PackageManagerService main(Context context, Installer installer,
1742            boolean factoryTest, boolean onlyCore) {
1743        PackageManagerService m = new PackageManagerService(context, installer,
1744                factoryTest, onlyCore);
1745        ServiceManager.addService("package", m);
1746        return m;
1747    }
1748
1749    static String[] splitString(String str, char sep) {
1750        int count = 1;
1751        int i = 0;
1752        while ((i=str.indexOf(sep, i)) >= 0) {
1753            count++;
1754            i++;
1755        }
1756
1757        String[] res = new String[count];
1758        i=0;
1759        count = 0;
1760        int lastI=0;
1761        while ((i=str.indexOf(sep, i)) >= 0) {
1762            res[count] = str.substring(lastI, i);
1763            count++;
1764            i++;
1765            lastI = i;
1766        }
1767        res[count] = str.substring(lastI, str.length());
1768        return res;
1769    }
1770
1771    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1772        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1773                Context.DISPLAY_SERVICE);
1774        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1775    }
1776
1777    public PackageManagerService(Context context, Installer installer,
1778            boolean factoryTest, boolean onlyCore) {
1779        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1780                SystemClock.uptimeMillis());
1781
1782        if (mSdkVersion <= 0) {
1783            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1784        }
1785
1786        mContext = context;
1787        mFactoryTest = factoryTest;
1788        mOnlyCore = onlyCore;
1789        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1790        mMetrics = new DisplayMetrics();
1791        mSettings = new Settings(mPackages);
1792        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1797                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1798        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804
1805        // TODO: add a property to control this?
1806        long dexOptLRUThresholdInMinutes;
1807        if (mLazyDexOpt) {
1808            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1809        } else {
1810            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1811        }
1812        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1813
1814        String separateProcesses = SystemProperties.get("debug.separate_processes");
1815        if (separateProcesses != null && separateProcesses.length() > 0) {
1816            if ("*".equals(separateProcesses)) {
1817                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1818                mSeparateProcesses = null;
1819                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1820            } else {
1821                mDefParseFlags = 0;
1822                mSeparateProcesses = separateProcesses.split(",");
1823                Slog.w(TAG, "Running with debug.separate_processes: "
1824                        + separateProcesses);
1825            }
1826        } else {
1827            mDefParseFlags = 0;
1828            mSeparateProcesses = null;
1829        }
1830
1831        mInstaller = installer;
1832        mPackageDexOptimizer = new PackageDexOptimizer(this);
1833        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1834
1835        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1836                FgThread.get().getLooper());
1837
1838        getDefaultDisplayMetrics(context, mMetrics);
1839
1840        SystemConfig systemConfig = SystemConfig.getInstance();
1841        mGlobalGids = systemConfig.getGlobalGids();
1842        mSystemPermissions = systemConfig.getSystemPermissions();
1843        mAvailableFeatures = systemConfig.getAvailableFeatures();
1844
1845        synchronized (mInstallLock) {
1846        // writer
1847        synchronized (mPackages) {
1848            mHandlerThread = new ServiceThread(TAG,
1849                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1850            mHandlerThread.start();
1851            mHandler = new PackageHandler(mHandlerThread.getLooper());
1852            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1853
1854            File dataDir = Environment.getDataDirectory();
1855            mAppDataDir = new File(dataDir, "data");
1856            mAppInstallDir = new File(dataDir, "app");
1857            mAppLib32InstallDir = new File(dataDir, "app-lib");
1858            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1859            mUserAppDataDir = new File(dataDir, "user");
1860            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1861
1862            sUserManager = new UserManagerService(context, this,
1863                    mInstallLock, mPackages);
1864
1865            // Propagate permission configuration in to package manager.
1866            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1867                    = systemConfig.getPermissions();
1868            for (int i=0; i<permConfig.size(); i++) {
1869                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1870                BasePermission bp = mSettings.mPermissions.get(perm.name);
1871                if (bp == null) {
1872                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1873                    mSettings.mPermissions.put(perm.name, bp);
1874                }
1875                if (perm.gids != null) {
1876                    bp.setGids(perm.gids, perm.perUser);
1877                }
1878            }
1879
1880            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1881            for (int i=0; i<libConfig.size(); i++) {
1882                mSharedLibraries.put(libConfig.keyAt(i),
1883                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1884            }
1885
1886            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1887
1888            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1889                    mSdkVersion, mOnlyCore);
1890
1891            String customResolverActivity = Resources.getSystem().getString(
1892                    R.string.config_customResolverActivity);
1893            if (TextUtils.isEmpty(customResolverActivity)) {
1894                customResolverActivity = null;
1895            } else {
1896                mCustomResolverComponentName = ComponentName.unflattenFromString(
1897                        customResolverActivity);
1898            }
1899
1900            long startTime = SystemClock.uptimeMillis();
1901
1902            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1903                    startTime);
1904
1905            // Set flag to monitor and not change apk file paths when
1906            // scanning install directories.
1907            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1908
1909            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1910
1911            /**
1912             * Add everything in the in the boot class path to the
1913             * list of process files because dexopt will have been run
1914             * if necessary during zygote startup.
1915             */
1916            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1917            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1918
1919            if (bootClassPath != null) {
1920                String[] bootClassPathElements = splitString(bootClassPath, ':');
1921                for (String element : bootClassPathElements) {
1922                    alreadyDexOpted.add(element);
1923                }
1924            } else {
1925                Slog.w(TAG, "No BOOTCLASSPATH found!");
1926            }
1927
1928            if (systemServerClassPath != null) {
1929                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1930                for (String element : systemServerClassPathElements) {
1931                    alreadyDexOpted.add(element);
1932                }
1933            } else {
1934                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1935            }
1936
1937            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1938            final String[] dexCodeInstructionSets =
1939                    getDexCodeInstructionSets(
1940                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1941
1942            /**
1943             * Ensure all external libraries have had dexopt run on them.
1944             */
1945            if (mSharedLibraries.size() > 0) {
1946                // NOTE: For now, we're compiling these system "shared libraries"
1947                // (and framework jars) into all available architectures. It's possible
1948                // to compile them only when we come across an app that uses them (there's
1949                // already logic for that in scanPackageLI) but that adds some complexity.
1950                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1951                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1952                        final String lib = libEntry.path;
1953                        if (lib == null) {
1954                            continue;
1955                        }
1956
1957                        try {
1958                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1959                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1960                                alreadyDexOpted.add(lib);
1961                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1962                            }
1963                        } catch (FileNotFoundException e) {
1964                            Slog.w(TAG, "Library not found: " + lib);
1965                        } catch (IOException e) {
1966                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1967                                    + e.getMessage());
1968                        }
1969                    }
1970                }
1971            }
1972
1973            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1974
1975            // Gross hack for now: we know this file doesn't contain any
1976            // code, so don't dexopt it to avoid the resulting log spew.
1977            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1978
1979            // Gross hack for now: we know this file is only part of
1980            // the boot class path for art, so don't dexopt it to
1981            // avoid the resulting log spew.
1982            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1983
1984            /**
1985             * There are a number of commands implemented in Java, which
1986             * we currently need to do the dexopt on so that they can be
1987             * run from a non-root shell.
1988             */
1989            String[] frameworkFiles = frameworkDir.list();
1990            if (frameworkFiles != null) {
1991                // TODO: We could compile these only for the most preferred ABI. We should
1992                // first double check that the dex files for these commands are not referenced
1993                // by other system apps.
1994                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1995                    for (int i=0; i<frameworkFiles.length; i++) {
1996                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1997                        String path = libPath.getPath();
1998                        // Skip the file if we already did it.
1999                        if (alreadyDexOpted.contains(path)) {
2000                            continue;
2001                        }
2002                        // Skip the file if it is not a type we want to dexopt.
2003                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2004                            continue;
2005                        }
2006                        try {
2007                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2008                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2009                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2010                            }
2011                        } catch (FileNotFoundException e) {
2012                            Slog.w(TAG, "Jar not found: " + path);
2013                        } catch (IOException e) {
2014                            Slog.w(TAG, "Exception reading jar: " + path, e);
2015                        }
2016                    }
2017                }
2018            }
2019
2020            // Collect vendor overlay packages.
2021            // (Do this before scanning any apps.)
2022            // For security and version matching reason, only consider
2023            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2024            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2025            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2026                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2027
2028            // Find base frameworks (resource packages without code).
2029            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2030                    | PackageParser.PARSE_IS_SYSTEM_DIR
2031                    | PackageParser.PARSE_IS_PRIVILEGED,
2032                    scanFlags | SCAN_NO_DEX, 0);
2033
2034            // Collected privileged system packages.
2035            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2036            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2037                    | PackageParser.PARSE_IS_SYSTEM_DIR
2038                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2039
2040            // Collect ordinary system packages.
2041            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2042            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2043                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2044
2045            // Collect all vendor packages.
2046            File vendorAppDir = new File("/vendor/app");
2047            try {
2048                vendorAppDir = vendorAppDir.getCanonicalFile();
2049            } catch (IOException e) {
2050                // failed to look up canonical path, continue with original one
2051            }
2052            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2053                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2054
2055            // Collect all OEM packages.
2056            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2057            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2058                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2059
2060            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2061            mInstaller.moveFiles();
2062
2063            // Prune any system packages that no longer exist.
2064            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2065            if (!mOnlyCore) {
2066                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2067                while (psit.hasNext()) {
2068                    PackageSetting ps = psit.next();
2069
2070                    /*
2071                     * If this is not a system app, it can't be a
2072                     * disable system app.
2073                     */
2074                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2075                        continue;
2076                    }
2077
2078                    /*
2079                     * If the package is scanned, it's not erased.
2080                     */
2081                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2082                    if (scannedPkg != null) {
2083                        /*
2084                         * If the system app is both scanned and in the
2085                         * disabled packages list, then it must have been
2086                         * added via OTA. Remove it from the currently
2087                         * scanned package so the previously user-installed
2088                         * application can be scanned.
2089                         */
2090                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2091                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2092                                    + ps.name + "; removing system app.  Last known codePath="
2093                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2094                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2095                                    + scannedPkg.mVersionCode);
2096                            removePackageLI(ps, true);
2097                            mExpectingBetter.put(ps.name, ps.codePath);
2098                        }
2099
2100                        continue;
2101                    }
2102
2103                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2104                        psit.remove();
2105                        logCriticalInfo(Log.WARN, "System package " + ps.name
2106                                + " no longer exists; wiping its data");
2107                        removeDataDirsLI(null, ps.name);
2108                    } else {
2109                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2110                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2111                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2112                        }
2113                    }
2114                }
2115            }
2116
2117            //look for any incomplete package installations
2118            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2119            //clean up list
2120            for(int i = 0; i < deletePkgsList.size(); i++) {
2121                //clean up here
2122                cleanupInstallFailedPackage(deletePkgsList.get(i));
2123            }
2124            //delete tmp files
2125            deleteTempPackageFiles();
2126
2127            // Remove any shared userIDs that have no associated packages
2128            mSettings.pruneSharedUsersLPw();
2129
2130            if (!mOnlyCore) {
2131                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2132                        SystemClock.uptimeMillis());
2133                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2134
2135                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2136                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2137
2138                /**
2139                 * Remove disable package settings for any updated system
2140                 * apps that were removed via an OTA. If they're not a
2141                 * previously-updated app, remove them completely.
2142                 * Otherwise, just revoke their system-level permissions.
2143                 */
2144                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2145                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2146                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2147
2148                    String msg;
2149                    if (deletedPkg == null) {
2150                        msg = "Updated system package " + deletedAppName
2151                                + " no longer exists; wiping its data";
2152                        removeDataDirsLI(null, deletedAppName);
2153                    } else {
2154                        msg = "Updated system app + " + deletedAppName
2155                                + " no longer present; removing system privileges for "
2156                                + deletedAppName;
2157
2158                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2159
2160                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2161                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2162                    }
2163                    logCriticalInfo(Log.WARN, msg);
2164                }
2165
2166                /**
2167                 * Make sure all system apps that we expected to appear on
2168                 * the userdata partition actually showed up. If they never
2169                 * appeared, crawl back and revive the system version.
2170                 */
2171                for (int i = 0; i < mExpectingBetter.size(); i++) {
2172                    final String packageName = mExpectingBetter.keyAt(i);
2173                    if (!mPackages.containsKey(packageName)) {
2174                        final File scanFile = mExpectingBetter.valueAt(i);
2175
2176                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2177                                + " but never showed up; reverting to system");
2178
2179                        final int reparseFlags;
2180                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2181                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2182                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2183                                    | PackageParser.PARSE_IS_PRIVILEGED;
2184                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2185                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2186                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2187                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2188                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2189                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2190                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2191                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2192                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2193                        } else {
2194                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2195                            continue;
2196                        }
2197
2198                        mSettings.enableSystemPackageLPw(packageName);
2199
2200                        try {
2201                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2202                        } catch (PackageManagerException e) {
2203                            Slog.e(TAG, "Failed to parse original system package: "
2204                                    + e.getMessage());
2205                        }
2206                    }
2207                }
2208            }
2209            mExpectingBetter.clear();
2210
2211            // Now that we know all of the shared libraries, update all clients to have
2212            // the correct library paths.
2213            updateAllSharedLibrariesLPw();
2214
2215            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2216                // NOTE: We ignore potential failures here during a system scan (like
2217                // the rest of the commands above) because there's precious little we
2218                // can do about it. A settings error is reported, though.
2219                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2220                        false /* force dexopt */, false /* defer dexopt */);
2221            }
2222
2223            // Now that we know all the packages we are keeping,
2224            // read and update their last usage times.
2225            mPackageUsage.readLP();
2226
2227            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2228                    SystemClock.uptimeMillis());
2229            Slog.i(TAG, "Time to scan packages: "
2230                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2231                    + " seconds");
2232
2233            // If the platform SDK has changed since the last time we booted,
2234            // we need to re-grant app permission to catch any new ones that
2235            // appear.  This is really a hack, and means that apps can in some
2236            // cases get permissions that the user didn't initially explicitly
2237            // allow...  it would be nice to have some better way to handle
2238            // this situation.
2239            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2240                    != mSdkVersion;
2241            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2242                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2243                    + "; regranting permissions for internal storage");
2244            mSettings.mInternalSdkPlatform = mSdkVersion;
2245
2246            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2247                    | (regrantPermissions
2248                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2249                            : 0));
2250
2251            // If this is the first boot, and it is a normal boot, then
2252            // we need to initialize the default preferred apps.
2253            if (!mRestoredSettings && !onlyCore) {
2254                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2255                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2256                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2257            }
2258
2259            // If this is first boot after an OTA, and a normal boot, then
2260            // we need to clear code cache directories.
2261            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2262            if (mIsUpgrade && !onlyCore) {
2263                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2264                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2265                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2266                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2267                }
2268                mSettings.mFingerprint = Build.FINGERPRINT;
2269            }
2270
2271            checkDefaultBrowser();
2272
2273            // All the changes are done during package scanning.
2274            mSettings.updateInternalDatabaseVersion();
2275
2276            // can downgrade to reader
2277            mSettings.writeLPr();
2278
2279            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2280                    SystemClock.uptimeMillis());
2281
2282            mRequiredVerifierPackage = getRequiredVerifierLPr();
2283            mRequiredInstallerPackage = getRequiredInstallerLPr();
2284
2285            mInstallerService = new PackageInstallerService(context, this);
2286
2287            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2288            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2289                    mIntentFilterVerifierComponent);
2290
2291        } // synchronized (mPackages)
2292        } // synchronized (mInstallLock)
2293
2294        // Now after opening every single application zip, make sure they
2295        // are all flushed.  Not really needed, but keeps things nice and
2296        // tidy.
2297        Runtime.getRuntime().gc();
2298
2299        // Expose private service for system components to use.
2300        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2301    }
2302
2303    @Override
2304    public boolean isFirstBoot() {
2305        return !mRestoredSettings;
2306    }
2307
2308    @Override
2309    public boolean isOnlyCoreApps() {
2310        return mOnlyCore;
2311    }
2312
2313    @Override
2314    public boolean isUpgrade() {
2315        return mIsUpgrade;
2316    }
2317
2318    private String getRequiredVerifierLPr() {
2319        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2320        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2321                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2322
2323        String requiredVerifier = null;
2324
2325        final int N = receivers.size();
2326        for (int i = 0; i < N; i++) {
2327            final ResolveInfo info = receivers.get(i);
2328
2329            if (info.activityInfo == null) {
2330                continue;
2331            }
2332
2333            final String packageName = info.activityInfo.packageName;
2334
2335            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2336                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2337                continue;
2338            }
2339
2340            if (requiredVerifier != null) {
2341                throw new RuntimeException("There can be only one required verifier");
2342            }
2343
2344            requiredVerifier = packageName;
2345        }
2346
2347        return requiredVerifier;
2348    }
2349
2350    private String getRequiredInstallerLPr() {
2351        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2352        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2353        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2354
2355        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2356                PACKAGE_MIME_TYPE, 0, 0);
2357
2358        String requiredInstaller = null;
2359
2360        final int N = installers.size();
2361        for (int i = 0; i < N; i++) {
2362            final ResolveInfo info = installers.get(i);
2363            final String packageName = info.activityInfo.packageName;
2364
2365            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2366                continue;
2367            }
2368
2369            if (requiredInstaller != null) {
2370                throw new RuntimeException("There must be one required installer");
2371            }
2372
2373            requiredInstaller = packageName;
2374        }
2375
2376        if (requiredInstaller == null) {
2377            throw new RuntimeException("There must be one required installer");
2378        }
2379
2380        return requiredInstaller;
2381    }
2382
2383    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2384        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2385        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2386                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2387
2388        ComponentName verifierComponentName = null;
2389
2390        int priority = -1000;
2391        final int N = receivers.size();
2392        for (int i = 0; i < N; i++) {
2393            final ResolveInfo info = receivers.get(i);
2394
2395            if (info.activityInfo == null) {
2396                continue;
2397            }
2398
2399            final String packageName = info.activityInfo.packageName;
2400
2401            final PackageSetting ps = mSettings.mPackages.get(packageName);
2402            if (ps == null) {
2403                continue;
2404            }
2405
2406            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2407                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2408                continue;
2409            }
2410
2411            // Select the IntentFilterVerifier with the highest priority
2412            if (priority < info.priority) {
2413                priority = info.priority;
2414                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2415                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2416                        + verifierComponentName + " with priority: " + info.priority);
2417            }
2418        }
2419
2420        return verifierComponentName;
2421    }
2422
2423    private void primeDomainVerificationsLPw(int userId) {
2424        if (DEBUG_DOMAIN_VERIFICATION) {
2425            Slog.d(TAG, "Priming domain verifications in user " + userId);
2426        }
2427
2428        SystemConfig systemConfig = SystemConfig.getInstance();
2429        ArraySet<String> packages = systemConfig.getLinkedApps();
2430        ArraySet<String> domains = new ArraySet<String>();
2431
2432        for (String packageName : packages) {
2433            PackageParser.Package pkg = mPackages.get(packageName);
2434            if (pkg != null) {
2435                if (!pkg.isSystemApp()) {
2436                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2437                    continue;
2438                }
2439
2440                domains.clear();
2441                for (PackageParser.Activity a : pkg.activities) {
2442                    for (ActivityIntentInfo filter : a.intents) {
2443                        if (hasValidDomains(filter)) {
2444                            domains.addAll(filter.getHostsList());
2445                        }
2446                    }
2447                }
2448
2449                if (domains.size() > 0) {
2450                    if (DEBUG_DOMAIN_VERIFICATION) {
2451                        Slog.v(TAG, "      + " + packageName);
2452                    }
2453                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2454                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2455                    // and then 'always' in the per-user state actually used for intent resolution.
2456                    final IntentFilterVerificationInfo ivi;
2457                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2458                            new ArrayList<String>(domains));
2459                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2460                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2461                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2462                } else {
2463                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2464                            + "' does not handle web links");
2465                }
2466            } else {
2467                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2468            }
2469        }
2470
2471        scheduleWritePackageRestrictionsLocked(userId);
2472        scheduleWriteSettingsLocked();
2473    }
2474
2475    private void applyFactoryDefaultBrowserLPw(int userId) {
2476        // The default browser app's package name is stored in a string resource,
2477        // with a product-specific overlay used for vendor customization.
2478        String browserPkg = mContext.getResources().getString(
2479                com.android.internal.R.string.default_browser);
2480        if (!TextUtils.isEmpty(browserPkg)) {
2481            // non-empty string => required to be a known package
2482            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2483            if (ps == null) {
2484                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2485                browserPkg = null;
2486            } else {
2487                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2488            }
2489        }
2490
2491        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2492        // default.  If there's more than one, just leave everything alone.
2493        if (browserPkg == null) {
2494            calculateDefaultBrowserLPw(userId);
2495        }
2496    }
2497
2498    private void calculateDefaultBrowserLPw(int userId) {
2499        List<String> allBrowsers = resolveAllBrowserApps(userId);
2500        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2501        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2502    }
2503
2504    private List<String> resolveAllBrowserApps(int userId) {
2505        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2506        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2507                PackageManager.MATCH_ALL, userId);
2508
2509        final int count = list.size();
2510        List<String> result = new ArrayList<String>(count);
2511        for (int i=0; i<count; i++) {
2512            ResolveInfo info = list.get(i);
2513            if (info.activityInfo == null
2514                    || !info.handleAllWebDataURI
2515                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2516                    || result.contains(info.activityInfo.packageName)) {
2517                continue;
2518            }
2519            result.add(info.activityInfo.packageName);
2520        }
2521
2522        return result;
2523    }
2524
2525    private boolean packageIsBrowser(String packageName, int userId) {
2526        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2527                PackageManager.MATCH_ALL, userId);
2528        final int N = list.size();
2529        for (int i = 0; i < N; i++) {
2530            ResolveInfo info = list.get(i);
2531            if (packageName.equals(info.activityInfo.packageName)) {
2532                return true;
2533            }
2534        }
2535        return false;
2536    }
2537
2538    private void checkDefaultBrowser() {
2539        final int myUserId = UserHandle.myUserId();
2540        final String packageName = getDefaultBrowserPackageName(myUserId);
2541        if (packageName != null) {
2542            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2543            if (info == null) {
2544                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2545                synchronized (mPackages) {
2546                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2547                }
2548            }
2549        }
2550    }
2551
2552    @Override
2553    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2554            throws RemoteException {
2555        try {
2556            return super.onTransact(code, data, reply, flags);
2557        } catch (RuntimeException e) {
2558            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2559                Slog.wtf(TAG, "Package Manager Crash", e);
2560            }
2561            throw e;
2562        }
2563    }
2564
2565    void cleanupInstallFailedPackage(PackageSetting ps) {
2566        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2567
2568        removeDataDirsLI(ps.volumeUuid, ps.name);
2569        if (ps.codePath != null) {
2570            if (ps.codePath.isDirectory()) {
2571                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2572            } else {
2573                ps.codePath.delete();
2574            }
2575        }
2576        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2577            if (ps.resourcePath.isDirectory()) {
2578                FileUtils.deleteContents(ps.resourcePath);
2579            }
2580            ps.resourcePath.delete();
2581        }
2582        mSettings.removePackageLPw(ps.name);
2583    }
2584
2585    static int[] appendInts(int[] cur, int[] add) {
2586        if (add == null) return cur;
2587        if (cur == null) return add;
2588        final int N = add.length;
2589        for (int i=0; i<N; i++) {
2590            cur = appendInt(cur, add[i]);
2591        }
2592        return cur;
2593    }
2594
2595    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2596        if (!sUserManager.exists(userId)) return null;
2597        final PackageSetting ps = (PackageSetting) p.mExtras;
2598        if (ps == null) {
2599            return null;
2600        }
2601
2602        final PermissionsState permissionsState = ps.getPermissionsState();
2603
2604        final int[] gids = permissionsState.computeGids(userId);
2605        final Set<String> permissions = permissionsState.getPermissions(userId);
2606        final PackageUserState state = ps.readUserState(userId);
2607
2608        return PackageParser.generatePackageInfo(p, gids, flags,
2609                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2610    }
2611
2612    @Override
2613    public boolean isPackageFrozen(String packageName) {
2614        synchronized (mPackages) {
2615            final PackageSetting ps = mSettings.mPackages.get(packageName);
2616            if (ps != null) {
2617                return ps.frozen;
2618            }
2619        }
2620        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2621        return true;
2622    }
2623
2624    @Override
2625    public boolean isPackageAvailable(String packageName, int userId) {
2626        if (!sUserManager.exists(userId)) return false;
2627        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2628        synchronized (mPackages) {
2629            PackageParser.Package p = mPackages.get(packageName);
2630            if (p != null) {
2631                final PackageSetting ps = (PackageSetting) p.mExtras;
2632                if (ps != null) {
2633                    final PackageUserState state = ps.readUserState(userId);
2634                    if (state != null) {
2635                        return PackageParser.isAvailable(state);
2636                    }
2637                }
2638            }
2639        }
2640        return false;
2641    }
2642
2643    @Override
2644    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2645        if (!sUserManager.exists(userId)) return null;
2646        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2647        // reader
2648        synchronized (mPackages) {
2649            PackageParser.Package p = mPackages.get(packageName);
2650            if (DEBUG_PACKAGE_INFO)
2651                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2652            if (p != null) {
2653                return generatePackageInfo(p, flags, userId);
2654            }
2655            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2656                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2657            }
2658        }
2659        return null;
2660    }
2661
2662    @Override
2663    public String[] currentToCanonicalPackageNames(String[] names) {
2664        String[] out = new String[names.length];
2665        // reader
2666        synchronized (mPackages) {
2667            for (int i=names.length-1; i>=0; i--) {
2668                PackageSetting ps = mSettings.mPackages.get(names[i]);
2669                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2670            }
2671        }
2672        return out;
2673    }
2674
2675    @Override
2676    public String[] canonicalToCurrentPackageNames(String[] names) {
2677        String[] out = new String[names.length];
2678        // reader
2679        synchronized (mPackages) {
2680            for (int i=names.length-1; i>=0; i--) {
2681                String cur = mSettings.mRenamedPackages.get(names[i]);
2682                out[i] = cur != null ? cur : names[i];
2683            }
2684        }
2685        return out;
2686    }
2687
2688    @Override
2689    public int getPackageUid(String packageName, int userId) {
2690        if (!sUserManager.exists(userId)) return -1;
2691        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2692
2693        // reader
2694        synchronized (mPackages) {
2695            PackageParser.Package p = mPackages.get(packageName);
2696            if(p != null) {
2697                return UserHandle.getUid(userId, p.applicationInfo.uid);
2698            }
2699            PackageSetting ps = mSettings.mPackages.get(packageName);
2700            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2701                return -1;
2702            }
2703            p = ps.pkg;
2704            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2705        }
2706    }
2707
2708    @Override
2709    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2710        if (!sUserManager.exists(userId)) {
2711            return null;
2712        }
2713
2714        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2715                "getPackageGids");
2716
2717        // reader
2718        synchronized (mPackages) {
2719            PackageParser.Package p = mPackages.get(packageName);
2720            if (DEBUG_PACKAGE_INFO) {
2721                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2722            }
2723            if (p != null) {
2724                PackageSetting ps = (PackageSetting) p.mExtras;
2725                return ps.getPermissionsState().computeGids(userId);
2726            }
2727        }
2728
2729        return null;
2730    }
2731
2732    static PermissionInfo generatePermissionInfo(
2733            BasePermission bp, int flags) {
2734        if (bp.perm != null) {
2735            return PackageParser.generatePermissionInfo(bp.perm, flags);
2736        }
2737        PermissionInfo pi = new PermissionInfo();
2738        pi.name = bp.name;
2739        pi.packageName = bp.sourcePackage;
2740        pi.nonLocalizedLabel = bp.name;
2741        pi.protectionLevel = bp.protectionLevel;
2742        return pi;
2743    }
2744
2745    @Override
2746    public PermissionInfo getPermissionInfo(String name, int flags) {
2747        // reader
2748        synchronized (mPackages) {
2749            final BasePermission p = mSettings.mPermissions.get(name);
2750            if (p != null) {
2751                return generatePermissionInfo(p, flags);
2752            }
2753            return null;
2754        }
2755    }
2756
2757    @Override
2758    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2759        // reader
2760        synchronized (mPackages) {
2761            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2762            for (BasePermission p : mSettings.mPermissions.values()) {
2763                if (group == null) {
2764                    if (p.perm == null || p.perm.info.group == null) {
2765                        out.add(generatePermissionInfo(p, flags));
2766                    }
2767                } else {
2768                    if (p.perm != null && group.equals(p.perm.info.group)) {
2769                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2770                    }
2771                }
2772            }
2773
2774            if (out.size() > 0) {
2775                return out;
2776            }
2777            return mPermissionGroups.containsKey(group) ? out : null;
2778        }
2779    }
2780
2781    @Override
2782    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2783        // reader
2784        synchronized (mPackages) {
2785            return PackageParser.generatePermissionGroupInfo(
2786                    mPermissionGroups.get(name), flags);
2787        }
2788    }
2789
2790    @Override
2791    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2792        // reader
2793        synchronized (mPackages) {
2794            final int N = mPermissionGroups.size();
2795            ArrayList<PermissionGroupInfo> out
2796                    = new ArrayList<PermissionGroupInfo>(N);
2797            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2798                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2799            }
2800            return out;
2801        }
2802    }
2803
2804    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2805            int userId) {
2806        if (!sUserManager.exists(userId)) return null;
2807        PackageSetting ps = mSettings.mPackages.get(packageName);
2808        if (ps != null) {
2809            if (ps.pkg == null) {
2810                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2811                        flags, userId);
2812                if (pInfo != null) {
2813                    return pInfo.applicationInfo;
2814                }
2815                return null;
2816            }
2817            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2818                    ps.readUserState(userId), userId);
2819        }
2820        return null;
2821    }
2822
2823    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2824            int userId) {
2825        if (!sUserManager.exists(userId)) return null;
2826        PackageSetting ps = mSettings.mPackages.get(packageName);
2827        if (ps != null) {
2828            PackageParser.Package pkg = ps.pkg;
2829            if (pkg == null) {
2830                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2831                    return null;
2832                }
2833                // Only data remains, so we aren't worried about code paths
2834                pkg = new PackageParser.Package(packageName);
2835                pkg.applicationInfo.packageName = packageName;
2836                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2837                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2838                pkg.applicationInfo.dataDir = Environment
2839                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2840                        .getAbsolutePath();
2841                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2842                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2843            }
2844            return generatePackageInfo(pkg, flags, userId);
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2851        if (!sUserManager.exists(userId)) return null;
2852        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2853        // writer
2854        synchronized (mPackages) {
2855            PackageParser.Package p = mPackages.get(packageName);
2856            if (DEBUG_PACKAGE_INFO) Log.v(
2857                    TAG, "getApplicationInfo " + packageName
2858                    + ": " + p);
2859            if (p != null) {
2860                PackageSetting ps = mSettings.mPackages.get(packageName);
2861                if (ps == null) return null;
2862                // Note: isEnabledLP() does not apply here - always return info
2863                return PackageParser.generateApplicationInfo(
2864                        p, flags, ps.readUserState(userId), userId);
2865            }
2866            if ("android".equals(packageName)||"system".equals(packageName)) {
2867                return mAndroidApplication;
2868            }
2869            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2870                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2871            }
2872        }
2873        return null;
2874    }
2875
2876    @Override
2877    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2878            final IPackageDataObserver observer) {
2879        mContext.enforceCallingOrSelfPermission(
2880                android.Manifest.permission.CLEAR_APP_CACHE, null);
2881        // Queue up an async operation since clearing cache may take a little while.
2882        mHandler.post(new Runnable() {
2883            public void run() {
2884                mHandler.removeCallbacks(this);
2885                int retCode = -1;
2886                synchronized (mInstallLock) {
2887                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2888                    if (retCode < 0) {
2889                        Slog.w(TAG, "Couldn't clear application caches");
2890                    }
2891                }
2892                if (observer != null) {
2893                    try {
2894                        observer.onRemoveCompleted(null, (retCode >= 0));
2895                    } catch (RemoteException e) {
2896                        Slog.w(TAG, "RemoveException when invoking call back");
2897                    }
2898                }
2899            }
2900        });
2901    }
2902
2903    @Override
2904    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2905            final IntentSender pi) {
2906        mContext.enforceCallingOrSelfPermission(
2907                android.Manifest.permission.CLEAR_APP_CACHE, null);
2908        // Queue up an async operation since clearing cache may take a little while.
2909        mHandler.post(new Runnable() {
2910            public void run() {
2911                mHandler.removeCallbacks(this);
2912                int retCode = -1;
2913                synchronized (mInstallLock) {
2914                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2915                    if (retCode < 0) {
2916                        Slog.w(TAG, "Couldn't clear application caches");
2917                    }
2918                }
2919                if(pi != null) {
2920                    try {
2921                        // Callback via pending intent
2922                        int code = (retCode >= 0) ? 1 : 0;
2923                        pi.sendIntent(null, code, null,
2924                                null, null);
2925                    } catch (SendIntentException e1) {
2926                        Slog.i(TAG, "Failed to send pending intent");
2927                    }
2928                }
2929            }
2930        });
2931    }
2932
2933    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2934        synchronized (mInstallLock) {
2935            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2936                throw new IOException("Failed to free enough space");
2937            }
2938        }
2939    }
2940
2941    @Override
2942    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2943        if (!sUserManager.exists(userId)) return null;
2944        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2945        synchronized (mPackages) {
2946            PackageParser.Activity a = mActivities.mActivities.get(component);
2947
2948            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2949            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2950                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2951                if (ps == null) return null;
2952                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2953                        userId);
2954            }
2955            if (mResolveComponentName.equals(component)) {
2956                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2957                        new PackageUserState(), userId);
2958            }
2959        }
2960        return null;
2961    }
2962
2963    @Override
2964    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2965            String resolvedType) {
2966        synchronized (mPackages) {
2967            PackageParser.Activity a = mActivities.mActivities.get(component);
2968            if (a == null) {
2969                return false;
2970            }
2971            for (int i=0; i<a.intents.size(); i++) {
2972                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2973                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2974                    return true;
2975                }
2976            }
2977            return false;
2978        }
2979    }
2980
2981    @Override
2982    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2983        if (!sUserManager.exists(userId)) return null;
2984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2985        synchronized (mPackages) {
2986            PackageParser.Activity a = mReceivers.mActivities.get(component);
2987            if (DEBUG_PACKAGE_INFO) Log.v(
2988                TAG, "getReceiverInfo " + component + ": " + a);
2989            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2990                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2991                if (ps == null) return null;
2992                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2993                        userId);
2994            }
2995        }
2996        return null;
2997    }
2998
2999    @Override
3000    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3001        if (!sUserManager.exists(userId)) return null;
3002        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3003        synchronized (mPackages) {
3004            PackageParser.Service s = mServices.mServices.get(component);
3005            if (DEBUG_PACKAGE_INFO) Log.v(
3006                TAG, "getServiceInfo " + component + ": " + s);
3007            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3008                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3009                if (ps == null) return null;
3010                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3011                        userId);
3012            }
3013        }
3014        return null;
3015    }
3016
3017    @Override
3018    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3021        synchronized (mPackages) {
3022            PackageParser.Provider p = mProviders.mProviders.get(component);
3023            if (DEBUG_PACKAGE_INFO) Log.v(
3024                TAG, "getProviderInfo " + component + ": " + p);
3025            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3026                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3027                if (ps == null) return null;
3028                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3029                        userId);
3030            }
3031        }
3032        return null;
3033    }
3034
3035    @Override
3036    public String[] getSystemSharedLibraryNames() {
3037        Set<String> libSet;
3038        synchronized (mPackages) {
3039            libSet = mSharedLibraries.keySet();
3040            int size = libSet.size();
3041            if (size > 0) {
3042                String[] libs = new String[size];
3043                libSet.toArray(libs);
3044                return libs;
3045            }
3046        }
3047        return null;
3048    }
3049
3050    /**
3051     * @hide
3052     */
3053    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3054        synchronized (mPackages) {
3055            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3056            if (lib != null && lib.apk != null) {
3057                return mPackages.get(lib.apk);
3058            }
3059        }
3060        return null;
3061    }
3062
3063    @Override
3064    public FeatureInfo[] getSystemAvailableFeatures() {
3065        Collection<FeatureInfo> featSet;
3066        synchronized (mPackages) {
3067            featSet = mAvailableFeatures.values();
3068            int size = featSet.size();
3069            if (size > 0) {
3070                FeatureInfo[] features = new FeatureInfo[size+1];
3071                featSet.toArray(features);
3072                FeatureInfo fi = new FeatureInfo();
3073                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3074                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3075                features[size] = fi;
3076                return features;
3077            }
3078        }
3079        return null;
3080    }
3081
3082    @Override
3083    public boolean hasSystemFeature(String name) {
3084        synchronized (mPackages) {
3085            return mAvailableFeatures.containsKey(name);
3086        }
3087    }
3088
3089    private void checkValidCaller(int uid, int userId) {
3090        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3091            return;
3092
3093        throw new SecurityException("Caller uid=" + uid
3094                + " is not privileged to communicate with user=" + userId);
3095    }
3096
3097    @Override
3098    public int checkPermission(String permName, String pkgName, int userId) {
3099        if (!sUserManager.exists(userId)) {
3100            return PackageManager.PERMISSION_DENIED;
3101        }
3102
3103        synchronized (mPackages) {
3104            final PackageParser.Package p = mPackages.get(pkgName);
3105            if (p != null && p.mExtras != null) {
3106                final PackageSetting ps = (PackageSetting) p.mExtras;
3107                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3108                    return PackageManager.PERMISSION_GRANTED;
3109                }
3110            }
3111        }
3112
3113        return PackageManager.PERMISSION_DENIED;
3114    }
3115
3116    @Override
3117    public int checkUidPermission(String permName, int uid) {
3118        final int userId = UserHandle.getUserId(uid);
3119
3120        if (!sUserManager.exists(userId)) {
3121            return PackageManager.PERMISSION_DENIED;
3122        }
3123
3124        synchronized (mPackages) {
3125            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3126            if (obj != null) {
3127                final SettingBase ps = (SettingBase) obj;
3128                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3129                    return PackageManager.PERMISSION_GRANTED;
3130                }
3131            } else {
3132                ArraySet<String> perms = mSystemPermissions.get(uid);
3133                if (perms != null && perms.contains(permName)) {
3134                    return PackageManager.PERMISSION_GRANTED;
3135                }
3136            }
3137        }
3138
3139        return PackageManager.PERMISSION_DENIED;
3140    }
3141
3142    @Override
3143    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3144        if (UserHandle.getCallingUserId() != userId) {
3145            mContext.enforceCallingPermission(
3146                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3147                    "isPermissionRevokedByPolicy for user " + userId);
3148        }
3149
3150        if (checkPermission(permission, packageName, userId)
3151                == PackageManager.PERMISSION_GRANTED) {
3152            return false;
3153        }
3154
3155        final long identity = Binder.clearCallingIdentity();
3156        try {
3157            final int flags = getPermissionFlags(permission, packageName, userId);
3158            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3159        } finally {
3160            Binder.restoreCallingIdentity(identity);
3161        }
3162    }
3163
3164    /**
3165     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3166     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3167     * @param checkShell TODO(yamasani):
3168     * @param message the message to log on security exception
3169     */
3170    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3171            boolean checkShell, String message) {
3172        if (userId < 0) {
3173            throw new IllegalArgumentException("Invalid userId " + userId);
3174        }
3175        if (checkShell) {
3176            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3177        }
3178        if (userId == UserHandle.getUserId(callingUid)) return;
3179        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3180            if (requireFullPermission) {
3181                mContext.enforceCallingOrSelfPermission(
3182                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3183            } else {
3184                try {
3185                    mContext.enforceCallingOrSelfPermission(
3186                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3187                } catch (SecurityException se) {
3188                    mContext.enforceCallingOrSelfPermission(
3189                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3190                }
3191            }
3192        }
3193    }
3194
3195    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3196        if (callingUid == Process.SHELL_UID) {
3197            if (userHandle >= 0
3198                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3199                throw new SecurityException("Shell does not have permission to access user "
3200                        + userHandle);
3201            } else if (userHandle < 0) {
3202                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3203                        + Debug.getCallers(3));
3204            }
3205        }
3206    }
3207
3208    private BasePermission findPermissionTreeLP(String permName) {
3209        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3210            if (permName.startsWith(bp.name) &&
3211                    permName.length() > bp.name.length() &&
3212                    permName.charAt(bp.name.length()) == '.') {
3213                return bp;
3214            }
3215        }
3216        return null;
3217    }
3218
3219    private BasePermission checkPermissionTreeLP(String permName) {
3220        if (permName != null) {
3221            BasePermission bp = findPermissionTreeLP(permName);
3222            if (bp != null) {
3223                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3224                    return bp;
3225                }
3226                throw new SecurityException("Calling uid "
3227                        + Binder.getCallingUid()
3228                        + " is not allowed to add to permission tree "
3229                        + bp.name + " owned by uid " + bp.uid);
3230            }
3231        }
3232        throw new SecurityException("No permission tree found for " + permName);
3233    }
3234
3235    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3236        if (s1 == null) {
3237            return s2 == null;
3238        }
3239        if (s2 == null) {
3240            return false;
3241        }
3242        if (s1.getClass() != s2.getClass()) {
3243            return false;
3244        }
3245        return s1.equals(s2);
3246    }
3247
3248    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3249        if (pi1.icon != pi2.icon) return false;
3250        if (pi1.logo != pi2.logo) return false;
3251        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3252        if (!compareStrings(pi1.name, pi2.name)) return false;
3253        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3254        // We'll take care of setting this one.
3255        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3256        // These are not currently stored in settings.
3257        //if (!compareStrings(pi1.group, pi2.group)) return false;
3258        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3259        //if (pi1.labelRes != pi2.labelRes) return false;
3260        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3261        return true;
3262    }
3263
3264    int permissionInfoFootprint(PermissionInfo info) {
3265        int size = info.name.length();
3266        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3267        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3268        return size;
3269    }
3270
3271    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3272        int size = 0;
3273        for (BasePermission perm : mSettings.mPermissions.values()) {
3274            if (perm.uid == tree.uid) {
3275                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3276            }
3277        }
3278        return size;
3279    }
3280
3281    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3282        // We calculate the max size of permissions defined by this uid and throw
3283        // if that plus the size of 'info' would exceed our stated maximum.
3284        if (tree.uid != Process.SYSTEM_UID) {
3285            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3286            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3287                throw new SecurityException("Permission tree size cap exceeded");
3288            }
3289        }
3290    }
3291
3292    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3293        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3294            throw new SecurityException("Label must be specified in permission");
3295        }
3296        BasePermission tree = checkPermissionTreeLP(info.name);
3297        BasePermission bp = mSettings.mPermissions.get(info.name);
3298        boolean added = bp == null;
3299        boolean changed = true;
3300        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3301        if (added) {
3302            enforcePermissionCapLocked(info, tree);
3303            bp = new BasePermission(info.name, tree.sourcePackage,
3304                    BasePermission.TYPE_DYNAMIC);
3305        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3306            throw new SecurityException(
3307                    "Not allowed to modify non-dynamic permission "
3308                    + info.name);
3309        } else {
3310            if (bp.protectionLevel == fixedLevel
3311                    && bp.perm.owner.equals(tree.perm.owner)
3312                    && bp.uid == tree.uid
3313                    && comparePermissionInfos(bp.perm.info, info)) {
3314                changed = false;
3315            }
3316        }
3317        bp.protectionLevel = fixedLevel;
3318        info = new PermissionInfo(info);
3319        info.protectionLevel = fixedLevel;
3320        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3321        bp.perm.info.packageName = tree.perm.info.packageName;
3322        bp.uid = tree.uid;
3323        if (added) {
3324            mSettings.mPermissions.put(info.name, bp);
3325        }
3326        if (changed) {
3327            if (!async) {
3328                mSettings.writeLPr();
3329            } else {
3330                scheduleWriteSettingsLocked();
3331            }
3332        }
3333        return added;
3334    }
3335
3336    @Override
3337    public boolean addPermission(PermissionInfo info) {
3338        synchronized (mPackages) {
3339            return addPermissionLocked(info, false);
3340        }
3341    }
3342
3343    @Override
3344    public boolean addPermissionAsync(PermissionInfo info) {
3345        synchronized (mPackages) {
3346            return addPermissionLocked(info, true);
3347        }
3348    }
3349
3350    @Override
3351    public void removePermission(String name) {
3352        synchronized (mPackages) {
3353            checkPermissionTreeLP(name);
3354            BasePermission bp = mSettings.mPermissions.get(name);
3355            if (bp != null) {
3356                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3357                    throw new SecurityException(
3358                            "Not allowed to modify non-dynamic permission "
3359                            + name);
3360                }
3361                mSettings.mPermissions.remove(name);
3362                mSettings.writeLPr();
3363            }
3364        }
3365    }
3366
3367    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3368            BasePermission bp) {
3369        int index = pkg.requestedPermissions.indexOf(bp.name);
3370        if (index == -1) {
3371            throw new SecurityException("Package " + pkg.packageName
3372                    + " has not requested permission " + bp.name);
3373        }
3374        if (!bp.isRuntime()) {
3375            throw new SecurityException("Permission " + bp.name
3376                    + " is not a changeable permission type");
3377        }
3378    }
3379
3380    @Override
3381    public void grantRuntimePermission(String packageName, String name, final int userId) {
3382        if (!sUserManager.exists(userId)) {
3383            Log.e(TAG, "No such user:" + userId);
3384            return;
3385        }
3386
3387        mContext.enforceCallingOrSelfPermission(
3388                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3389                "grantRuntimePermission");
3390
3391        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3392                "grantRuntimePermission");
3393
3394        final int uid;
3395        final SettingBase sb;
3396
3397        synchronized (mPackages) {
3398            final PackageParser.Package pkg = mPackages.get(packageName);
3399            if (pkg == null) {
3400                throw new IllegalArgumentException("Unknown package: " + packageName);
3401            }
3402
3403            final BasePermission bp = mSettings.mPermissions.get(name);
3404            if (bp == null) {
3405                throw new IllegalArgumentException("Unknown permission: " + name);
3406            }
3407
3408            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3409
3410            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3411            sb = (SettingBase) pkg.mExtras;
3412            if (sb == null) {
3413                throw new IllegalArgumentException("Unknown package: " + packageName);
3414            }
3415
3416            final PermissionsState permissionsState = sb.getPermissionsState();
3417
3418            final int flags = permissionsState.getPermissionFlags(name, userId);
3419            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3420                throw new SecurityException("Cannot grant system fixed permission: "
3421                        + name + " for package: " + packageName);
3422            }
3423
3424            final int result = permissionsState.grantRuntimePermission(bp, userId);
3425            switch (result) {
3426                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3427                    return;
3428                }
3429
3430                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3431                    mHandler.post(new Runnable() {
3432                        @Override
3433                        public void run() {
3434                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3435                        }
3436                    });
3437                } break;
3438            }
3439
3440            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3441
3442            // Not critical if that is lost - app has to request again.
3443            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3444        }
3445
3446        // Only need to do this if user is initialized. Otherwise it's a new user
3447        // and there are no processes running as the user yet and there's no need
3448        // to make an expensive call to remount processes for the changed permissions.
3449        if (READ_EXTERNAL_STORAGE.equals(name)
3450                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3451            final long token = Binder.clearCallingIdentity();
3452            try {
3453                if (sUserManager.isInitialized(userId)) {
3454                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3455                            MountServiceInternal.class);
3456                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3457                }
3458            } finally {
3459                Binder.restoreCallingIdentity(token);
3460            }
3461        }
3462    }
3463
3464    @Override
3465    public void revokeRuntimePermission(String packageName, String name, int userId) {
3466        if (!sUserManager.exists(userId)) {
3467            Log.e(TAG, "No such user:" + userId);
3468            return;
3469        }
3470
3471        mContext.enforceCallingOrSelfPermission(
3472                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3473                "revokeRuntimePermission");
3474
3475        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3476                "revokeRuntimePermission");
3477
3478        final SettingBase sb;
3479
3480        synchronized (mPackages) {
3481            final PackageParser.Package pkg = mPackages.get(packageName);
3482            if (pkg == null) {
3483                throw new IllegalArgumentException("Unknown package: " + packageName);
3484            }
3485
3486            final BasePermission bp = mSettings.mPermissions.get(name);
3487            if (bp == null) {
3488                throw new IllegalArgumentException("Unknown permission: " + name);
3489            }
3490
3491            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3492
3493            sb = (SettingBase) pkg.mExtras;
3494            if (sb == null) {
3495                throw new IllegalArgumentException("Unknown package: " + packageName);
3496            }
3497
3498            final PermissionsState permissionsState = sb.getPermissionsState();
3499
3500            final int flags = permissionsState.getPermissionFlags(name, userId);
3501            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3502                throw new SecurityException("Cannot revoke system fixed permission: "
3503                        + name + " for package: " + packageName);
3504            }
3505
3506            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3507                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3508                return;
3509            }
3510
3511            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3512
3513            // Critical, after this call app should never have the permission.
3514            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3515        }
3516
3517        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3518    }
3519
3520    @Override
3521    public void resetRuntimePermissions() {
3522        mContext.enforceCallingOrSelfPermission(
3523                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3524                "revokeRuntimePermission");
3525
3526        int callingUid = Binder.getCallingUid();
3527        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3528            mContext.enforceCallingOrSelfPermission(
3529                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3530                    "resetRuntimePermissions");
3531        }
3532
3533        final int[] userIds;
3534
3535        synchronized (mPackages) {
3536            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3537            final int userCount = UserManagerService.getInstance().getUserIds().length;
3538            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3539        }
3540
3541        for (int userId : userIds) {
3542            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3543        }
3544    }
3545
3546    @Override
3547    public int getPermissionFlags(String name, String packageName, int userId) {
3548        if (!sUserManager.exists(userId)) {
3549            return 0;
3550        }
3551
3552        mContext.enforceCallingOrSelfPermission(
3553                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3554                "getPermissionFlags");
3555
3556        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3557                "getPermissionFlags");
3558
3559        synchronized (mPackages) {
3560            final PackageParser.Package pkg = mPackages.get(packageName);
3561            if (pkg == null) {
3562                throw new IllegalArgumentException("Unknown package: " + packageName);
3563            }
3564
3565            final BasePermission bp = mSettings.mPermissions.get(name);
3566            if (bp == null) {
3567                throw new IllegalArgumentException("Unknown permission: " + name);
3568            }
3569
3570            SettingBase sb = (SettingBase) pkg.mExtras;
3571            if (sb == null) {
3572                throw new IllegalArgumentException("Unknown package: " + packageName);
3573            }
3574
3575            PermissionsState permissionsState = sb.getPermissionsState();
3576            return permissionsState.getPermissionFlags(name, userId);
3577        }
3578    }
3579
3580    @Override
3581    public void updatePermissionFlags(String name, String packageName, int flagMask,
3582            int flagValues, int userId) {
3583        if (!sUserManager.exists(userId)) {
3584            return;
3585        }
3586
3587        mContext.enforceCallingOrSelfPermission(
3588                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3589                "updatePermissionFlags");
3590
3591        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3592                "updatePermissionFlags");
3593
3594        // Only the system can change system fixed flags.
3595        if (getCallingUid() != Process.SYSTEM_UID) {
3596            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3597            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3598        }
3599
3600        synchronized (mPackages) {
3601            final PackageParser.Package pkg = mPackages.get(packageName);
3602            if (pkg == null) {
3603                throw new IllegalArgumentException("Unknown package: " + packageName);
3604            }
3605
3606            final BasePermission bp = mSettings.mPermissions.get(name);
3607            if (bp == null) {
3608                throw new IllegalArgumentException("Unknown permission: " + name);
3609            }
3610
3611            SettingBase sb = (SettingBase) pkg.mExtras;
3612            if (sb == null) {
3613                throw new IllegalArgumentException("Unknown package: " + packageName);
3614            }
3615
3616            PermissionsState permissionsState = sb.getPermissionsState();
3617
3618            // Only the package manager can change flags for system component permissions.
3619            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3620            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3621                return;
3622            }
3623
3624            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3625
3626            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3627                // Install and runtime permissions are stored in different places,
3628                // so figure out what permission changed and persist the change.
3629                if (permissionsState.getInstallPermissionState(name) != null) {
3630                    scheduleWriteSettingsLocked();
3631                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3632                        || hadState) {
3633                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3634                }
3635            }
3636        }
3637    }
3638
3639    /**
3640     * Update the permission flags for all packages and runtime permissions of a user in order
3641     * to allow device or profile owner to remove POLICY_FIXED.
3642     */
3643    @Override
3644    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3645        if (!sUserManager.exists(userId)) {
3646            return;
3647        }
3648
3649        mContext.enforceCallingOrSelfPermission(
3650                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3651                "updatePermissionFlagsForAllApps");
3652
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3654                "updatePermissionFlagsForAllApps");
3655
3656        // Only the system can change system fixed flags.
3657        if (getCallingUid() != Process.SYSTEM_UID) {
3658            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3659            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3660        }
3661
3662        synchronized (mPackages) {
3663            boolean changed = false;
3664            final int packageCount = mPackages.size();
3665            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3666                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3667                SettingBase sb = (SettingBase) pkg.mExtras;
3668                if (sb == null) {
3669                    continue;
3670                }
3671                PermissionsState permissionsState = sb.getPermissionsState();
3672                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3673                        userId, flagMask, flagValues);
3674            }
3675            if (changed) {
3676                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3677            }
3678        }
3679    }
3680
3681    @Override
3682    public boolean shouldShowRequestPermissionRationale(String permissionName,
3683            String packageName, int userId) {
3684        if (UserHandle.getCallingUserId() != userId) {
3685            mContext.enforceCallingPermission(
3686                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3687                    "canShowRequestPermissionRationale for user " + userId);
3688        }
3689
3690        final int uid = getPackageUid(packageName, userId);
3691        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3692            return false;
3693        }
3694
3695        if (checkPermission(permissionName, packageName, userId)
3696                == PackageManager.PERMISSION_GRANTED) {
3697            return false;
3698        }
3699
3700        final int flags;
3701
3702        final long identity = Binder.clearCallingIdentity();
3703        try {
3704            flags = getPermissionFlags(permissionName,
3705                    packageName, userId);
3706        } finally {
3707            Binder.restoreCallingIdentity(identity);
3708        }
3709
3710        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3711                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3712                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3713
3714        if ((flags & fixedFlags) != 0) {
3715            return false;
3716        }
3717
3718        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3719    }
3720
3721    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3722        BasePermission bp = mSettings.mPermissions.get(permission);
3723        if (bp == null) {
3724            throw new SecurityException("Missing " + permission + " permission");
3725        }
3726
3727        SettingBase sb = (SettingBase) pkg.mExtras;
3728        PermissionsState permissionsState = sb.getPermissionsState();
3729
3730        if (permissionsState.grantInstallPermission(bp) !=
3731                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3732            scheduleWriteSettingsLocked();
3733        }
3734    }
3735
3736    @Override
3737    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3738        mContext.enforceCallingOrSelfPermission(
3739                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3740                "addOnPermissionsChangeListener");
3741
3742        synchronized (mPackages) {
3743            mOnPermissionChangeListeners.addListenerLocked(listener);
3744        }
3745    }
3746
3747    @Override
3748    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3749        synchronized (mPackages) {
3750            mOnPermissionChangeListeners.removeListenerLocked(listener);
3751        }
3752    }
3753
3754    @Override
3755    public boolean isProtectedBroadcast(String actionName) {
3756        synchronized (mPackages) {
3757            return mProtectedBroadcasts.contains(actionName);
3758        }
3759    }
3760
3761    @Override
3762    public int checkSignatures(String pkg1, String pkg2) {
3763        synchronized (mPackages) {
3764            final PackageParser.Package p1 = mPackages.get(pkg1);
3765            final PackageParser.Package p2 = mPackages.get(pkg2);
3766            if (p1 == null || p1.mExtras == null
3767                    || p2 == null || p2.mExtras == null) {
3768                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3769            }
3770            return compareSignatures(p1.mSignatures, p2.mSignatures);
3771        }
3772    }
3773
3774    @Override
3775    public int checkUidSignatures(int uid1, int uid2) {
3776        // Map to base uids.
3777        uid1 = UserHandle.getAppId(uid1);
3778        uid2 = UserHandle.getAppId(uid2);
3779        // reader
3780        synchronized (mPackages) {
3781            Signature[] s1;
3782            Signature[] s2;
3783            Object obj = mSettings.getUserIdLPr(uid1);
3784            if (obj != null) {
3785                if (obj instanceof SharedUserSetting) {
3786                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3787                } else if (obj instanceof PackageSetting) {
3788                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3789                } else {
3790                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3791                }
3792            } else {
3793                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3794            }
3795            obj = mSettings.getUserIdLPr(uid2);
3796            if (obj != null) {
3797                if (obj instanceof SharedUserSetting) {
3798                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3799                } else if (obj instanceof PackageSetting) {
3800                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3801                } else {
3802                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3803                }
3804            } else {
3805                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3806            }
3807            return compareSignatures(s1, s2);
3808        }
3809    }
3810
3811    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3812        final long identity = Binder.clearCallingIdentity();
3813        try {
3814            if (sb instanceof SharedUserSetting) {
3815                SharedUserSetting sus = (SharedUserSetting) sb;
3816                final int packageCount = sus.packages.size();
3817                for (int i = 0; i < packageCount; i++) {
3818                    PackageSetting susPs = sus.packages.valueAt(i);
3819                    if (userId == UserHandle.USER_ALL) {
3820                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3821                    } else {
3822                        final int uid = UserHandle.getUid(userId, susPs.appId);
3823                        killUid(uid, reason);
3824                    }
3825                }
3826            } else if (sb instanceof PackageSetting) {
3827                PackageSetting ps = (PackageSetting) sb;
3828                if (userId == UserHandle.USER_ALL) {
3829                    killApplication(ps.pkg.packageName, ps.appId, reason);
3830                } else {
3831                    final int uid = UserHandle.getUid(userId, ps.appId);
3832                    killUid(uid, reason);
3833                }
3834            }
3835        } finally {
3836            Binder.restoreCallingIdentity(identity);
3837        }
3838    }
3839
3840    private static void killUid(int uid, String reason) {
3841        IActivityManager am = ActivityManagerNative.getDefault();
3842        if (am != null) {
3843            try {
3844                am.killUid(uid, reason);
3845            } catch (RemoteException e) {
3846                /* ignore - same process */
3847            }
3848        }
3849    }
3850
3851    /**
3852     * Compares two sets of signatures. Returns:
3853     * <br />
3854     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3855     * <br />
3856     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3857     * <br />
3858     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3859     * <br />
3860     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3861     * <br />
3862     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3863     */
3864    static int compareSignatures(Signature[] s1, Signature[] s2) {
3865        if (s1 == null) {
3866            return s2 == null
3867                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3868                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3869        }
3870
3871        if (s2 == null) {
3872            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3873        }
3874
3875        if (s1.length != s2.length) {
3876            return PackageManager.SIGNATURE_NO_MATCH;
3877        }
3878
3879        // Since both signature sets are of size 1, we can compare without HashSets.
3880        if (s1.length == 1) {
3881            return s1[0].equals(s2[0]) ?
3882                    PackageManager.SIGNATURE_MATCH :
3883                    PackageManager.SIGNATURE_NO_MATCH;
3884        }
3885
3886        ArraySet<Signature> set1 = new ArraySet<Signature>();
3887        for (Signature sig : s1) {
3888            set1.add(sig);
3889        }
3890        ArraySet<Signature> set2 = new ArraySet<Signature>();
3891        for (Signature sig : s2) {
3892            set2.add(sig);
3893        }
3894        // Make sure s2 contains all signatures in s1.
3895        if (set1.equals(set2)) {
3896            return PackageManager.SIGNATURE_MATCH;
3897        }
3898        return PackageManager.SIGNATURE_NO_MATCH;
3899    }
3900
3901    /**
3902     * If the database version for this type of package (internal storage or
3903     * external storage) is less than the version where package signatures
3904     * were updated, return true.
3905     */
3906    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3907        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3908                DatabaseVersion.SIGNATURE_END_ENTITY))
3909                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3910                        DatabaseVersion.SIGNATURE_END_ENTITY));
3911    }
3912
3913    /**
3914     * Used for backward compatibility to make sure any packages with
3915     * certificate chains get upgraded to the new style. {@code existingSigs}
3916     * will be in the old format (since they were stored on disk from before the
3917     * system upgrade) and {@code scannedSigs} will be in the newer format.
3918     */
3919    private int compareSignaturesCompat(PackageSignatures existingSigs,
3920            PackageParser.Package scannedPkg) {
3921        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3922            return PackageManager.SIGNATURE_NO_MATCH;
3923        }
3924
3925        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3926        for (Signature sig : existingSigs.mSignatures) {
3927            existingSet.add(sig);
3928        }
3929        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3930        for (Signature sig : scannedPkg.mSignatures) {
3931            try {
3932                Signature[] chainSignatures = sig.getChainSignatures();
3933                for (Signature chainSig : chainSignatures) {
3934                    scannedCompatSet.add(chainSig);
3935                }
3936            } catch (CertificateEncodingException e) {
3937                scannedCompatSet.add(sig);
3938            }
3939        }
3940        /*
3941         * Make sure the expanded scanned set contains all signatures in the
3942         * existing one.
3943         */
3944        if (scannedCompatSet.equals(existingSet)) {
3945            // Migrate the old signatures to the new scheme.
3946            existingSigs.assignSignatures(scannedPkg.mSignatures);
3947            // The new KeySets will be re-added later in the scanning process.
3948            synchronized (mPackages) {
3949                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3950            }
3951            return PackageManager.SIGNATURE_MATCH;
3952        }
3953        return PackageManager.SIGNATURE_NO_MATCH;
3954    }
3955
3956    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3957        if (isExternal(scannedPkg)) {
3958            return mSettings.isExternalDatabaseVersionOlderThan(
3959                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3960        } else {
3961            return mSettings.isInternalDatabaseVersionOlderThan(
3962                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3963        }
3964    }
3965
3966    private int compareSignaturesRecover(PackageSignatures existingSigs,
3967            PackageParser.Package scannedPkg) {
3968        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3969            return PackageManager.SIGNATURE_NO_MATCH;
3970        }
3971
3972        String msg = null;
3973        try {
3974            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3975                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3976                        + scannedPkg.packageName);
3977                return PackageManager.SIGNATURE_MATCH;
3978            }
3979        } catch (CertificateException e) {
3980            msg = e.getMessage();
3981        }
3982
3983        logCriticalInfo(Log.INFO,
3984                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3985        return PackageManager.SIGNATURE_NO_MATCH;
3986    }
3987
3988    @Override
3989    public String[] getPackagesForUid(int uid) {
3990        uid = UserHandle.getAppId(uid);
3991        // reader
3992        synchronized (mPackages) {
3993            Object obj = mSettings.getUserIdLPr(uid);
3994            if (obj instanceof SharedUserSetting) {
3995                final SharedUserSetting sus = (SharedUserSetting) obj;
3996                final int N = sus.packages.size();
3997                final String[] res = new String[N];
3998                final Iterator<PackageSetting> it = sus.packages.iterator();
3999                int i = 0;
4000                while (it.hasNext()) {
4001                    res[i++] = it.next().name;
4002                }
4003                return res;
4004            } else if (obj instanceof PackageSetting) {
4005                final PackageSetting ps = (PackageSetting) obj;
4006                return new String[] { ps.name };
4007            }
4008        }
4009        return null;
4010    }
4011
4012    @Override
4013    public String getNameForUid(int uid) {
4014        // reader
4015        synchronized (mPackages) {
4016            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4017            if (obj instanceof SharedUserSetting) {
4018                final SharedUserSetting sus = (SharedUserSetting) obj;
4019                return sus.name + ":" + sus.userId;
4020            } else if (obj instanceof PackageSetting) {
4021                final PackageSetting ps = (PackageSetting) obj;
4022                return ps.name;
4023            }
4024        }
4025        return null;
4026    }
4027
4028    @Override
4029    public int getUidForSharedUser(String sharedUserName) {
4030        if(sharedUserName == null) {
4031            return -1;
4032        }
4033        // reader
4034        synchronized (mPackages) {
4035            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4036            if (suid == null) {
4037                return -1;
4038            }
4039            return suid.userId;
4040        }
4041    }
4042
4043    @Override
4044    public int getFlagsForUid(int uid) {
4045        synchronized (mPackages) {
4046            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4047            if (obj instanceof SharedUserSetting) {
4048                final SharedUserSetting sus = (SharedUserSetting) obj;
4049                return sus.pkgFlags;
4050            } else if (obj instanceof PackageSetting) {
4051                final PackageSetting ps = (PackageSetting) obj;
4052                return ps.pkgFlags;
4053            }
4054        }
4055        return 0;
4056    }
4057
4058    @Override
4059    public int getPrivateFlagsForUid(int uid) {
4060        synchronized (mPackages) {
4061            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4062            if (obj instanceof SharedUserSetting) {
4063                final SharedUserSetting sus = (SharedUserSetting) obj;
4064                return sus.pkgPrivateFlags;
4065            } else if (obj instanceof PackageSetting) {
4066                final PackageSetting ps = (PackageSetting) obj;
4067                return ps.pkgPrivateFlags;
4068            }
4069        }
4070        return 0;
4071    }
4072
4073    @Override
4074    public boolean isUidPrivileged(int uid) {
4075        uid = UserHandle.getAppId(uid);
4076        // reader
4077        synchronized (mPackages) {
4078            Object obj = mSettings.getUserIdLPr(uid);
4079            if (obj instanceof SharedUserSetting) {
4080                final SharedUserSetting sus = (SharedUserSetting) obj;
4081                final Iterator<PackageSetting> it = sus.packages.iterator();
4082                while (it.hasNext()) {
4083                    if (it.next().isPrivileged()) {
4084                        return true;
4085                    }
4086                }
4087            } else if (obj instanceof PackageSetting) {
4088                final PackageSetting ps = (PackageSetting) obj;
4089                return ps.isPrivileged();
4090            }
4091        }
4092        return false;
4093    }
4094
4095    @Override
4096    public String[] getAppOpPermissionPackages(String permissionName) {
4097        synchronized (mPackages) {
4098            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4099            if (pkgs == null) {
4100                return null;
4101            }
4102            return pkgs.toArray(new String[pkgs.size()]);
4103        }
4104    }
4105
4106    @Override
4107    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4108            int flags, int userId) {
4109        if (!sUserManager.exists(userId)) return null;
4110        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4111        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4112        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4113    }
4114
4115    @Override
4116    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4117            IntentFilter filter, int match, ComponentName activity) {
4118        final int userId = UserHandle.getCallingUserId();
4119        if (DEBUG_PREFERRED) {
4120            Log.v(TAG, "setLastChosenActivity intent=" + intent
4121                + " resolvedType=" + resolvedType
4122                + " flags=" + flags
4123                + " filter=" + filter
4124                + " match=" + match
4125                + " activity=" + activity);
4126            filter.dump(new PrintStreamPrinter(System.out), "    ");
4127        }
4128        intent.setComponent(null);
4129        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4130        // Find any earlier preferred or last chosen entries and nuke them
4131        findPreferredActivity(intent, resolvedType,
4132                flags, query, 0, false, true, false, userId);
4133        // Add the new activity as the last chosen for this filter
4134        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4135                "Setting last chosen");
4136    }
4137
4138    @Override
4139    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4140        final int userId = UserHandle.getCallingUserId();
4141        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4142        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4143        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4144                false, false, false, userId);
4145    }
4146
4147    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4148            int flags, List<ResolveInfo> query, int userId) {
4149        if (query != null) {
4150            final int N = query.size();
4151            if (N == 1) {
4152                return query.get(0);
4153            } else if (N > 1) {
4154                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4155                // If there is more than one activity with the same priority,
4156                // then let the user decide between them.
4157                ResolveInfo r0 = query.get(0);
4158                ResolveInfo r1 = query.get(1);
4159                if (DEBUG_INTENT_MATCHING || debug) {
4160                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4161                            + r1.activityInfo.name + "=" + r1.priority);
4162                }
4163                // If the first activity has a higher priority, or a different
4164                // default, then it is always desireable to pick it.
4165                if (r0.priority != r1.priority
4166                        || r0.preferredOrder != r1.preferredOrder
4167                        || r0.isDefault != r1.isDefault) {
4168                    return query.get(0);
4169                }
4170                // If we have saved a preference for a preferred activity for
4171                // this Intent, use that.
4172                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4173                        flags, query, r0.priority, true, false, debug, userId);
4174                if (ri != null) {
4175                    return ri;
4176                }
4177                if (userId != 0) {
4178                    ri = new ResolveInfo(mResolveInfo);
4179                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4180                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4181                            ri.activityInfo.applicationInfo);
4182                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4183                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4184                    return ri;
4185                }
4186                return mResolveInfo;
4187            }
4188        }
4189        return null;
4190    }
4191
4192    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4193            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4194        final int N = query.size();
4195        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4196                .get(userId);
4197        // Get the list of persistent preferred activities that handle the intent
4198        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4199        List<PersistentPreferredActivity> pprefs = ppir != null
4200                ? ppir.queryIntent(intent, resolvedType,
4201                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4202                : null;
4203        if (pprefs != null && pprefs.size() > 0) {
4204            final int M = pprefs.size();
4205            for (int i=0; i<M; i++) {
4206                final PersistentPreferredActivity ppa = pprefs.get(i);
4207                if (DEBUG_PREFERRED || debug) {
4208                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4209                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4210                            + "\n  component=" + ppa.mComponent);
4211                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4212                }
4213                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4214                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4215                if (DEBUG_PREFERRED || debug) {
4216                    Slog.v(TAG, "Found persistent preferred activity:");
4217                    if (ai != null) {
4218                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4219                    } else {
4220                        Slog.v(TAG, "  null");
4221                    }
4222                }
4223                if (ai == null) {
4224                    // This previously registered persistent preferred activity
4225                    // component is no longer known. Ignore it and do NOT remove it.
4226                    continue;
4227                }
4228                for (int j=0; j<N; j++) {
4229                    final ResolveInfo ri = query.get(j);
4230                    if (!ri.activityInfo.applicationInfo.packageName
4231                            .equals(ai.applicationInfo.packageName)) {
4232                        continue;
4233                    }
4234                    if (!ri.activityInfo.name.equals(ai.name)) {
4235                        continue;
4236                    }
4237                    //  Found a persistent preference that can handle the intent.
4238                    if (DEBUG_PREFERRED || debug) {
4239                        Slog.v(TAG, "Returning persistent preferred activity: " +
4240                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4241                    }
4242                    return ri;
4243                }
4244            }
4245        }
4246        return null;
4247    }
4248
4249    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4250            List<ResolveInfo> query, int priority, boolean always,
4251            boolean removeMatches, boolean debug, int userId) {
4252        if (!sUserManager.exists(userId)) return null;
4253        // writer
4254        synchronized (mPackages) {
4255            if (intent.getSelector() != null) {
4256                intent = intent.getSelector();
4257            }
4258            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4259
4260            // Try to find a matching persistent preferred activity.
4261            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4262                    debug, userId);
4263
4264            // If a persistent preferred activity matched, use it.
4265            if (pri != null) {
4266                return pri;
4267            }
4268
4269            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4270            // Get the list of preferred activities that handle the intent
4271            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4272            List<PreferredActivity> prefs = pir != null
4273                    ? pir.queryIntent(intent, resolvedType,
4274                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4275                    : null;
4276            if (prefs != null && prefs.size() > 0) {
4277                boolean changed = false;
4278                try {
4279                    // First figure out how good the original match set is.
4280                    // We will only allow preferred activities that came
4281                    // from the same match quality.
4282                    int match = 0;
4283
4284                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4285
4286                    final int N = query.size();
4287                    for (int j=0; j<N; j++) {
4288                        final ResolveInfo ri = query.get(j);
4289                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4290                                + ": 0x" + Integer.toHexString(match));
4291                        if (ri.match > match) {
4292                            match = ri.match;
4293                        }
4294                    }
4295
4296                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4297                            + Integer.toHexString(match));
4298
4299                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4300                    final int M = prefs.size();
4301                    for (int i=0; i<M; i++) {
4302                        final PreferredActivity pa = prefs.get(i);
4303                        if (DEBUG_PREFERRED || debug) {
4304                            Slog.v(TAG, "Checking PreferredActivity ds="
4305                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4306                                    + "\n  component=" + pa.mPref.mComponent);
4307                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4308                        }
4309                        if (pa.mPref.mMatch != match) {
4310                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4311                                    + Integer.toHexString(pa.mPref.mMatch));
4312                            continue;
4313                        }
4314                        // If it's not an "always" type preferred activity and that's what we're
4315                        // looking for, skip it.
4316                        if (always && !pa.mPref.mAlways) {
4317                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4318                            continue;
4319                        }
4320                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4321                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4322                        if (DEBUG_PREFERRED || debug) {
4323                            Slog.v(TAG, "Found preferred activity:");
4324                            if (ai != null) {
4325                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4326                            } else {
4327                                Slog.v(TAG, "  null");
4328                            }
4329                        }
4330                        if (ai == null) {
4331                            // This previously registered preferred activity
4332                            // component is no longer known.  Most likely an update
4333                            // to the app was installed and in the new version this
4334                            // component no longer exists.  Clean it up by removing
4335                            // it from the preferred activities list, and skip it.
4336                            Slog.w(TAG, "Removing dangling preferred activity: "
4337                                    + pa.mPref.mComponent);
4338                            pir.removeFilter(pa);
4339                            changed = true;
4340                            continue;
4341                        }
4342                        for (int j=0; j<N; j++) {
4343                            final ResolveInfo ri = query.get(j);
4344                            if (!ri.activityInfo.applicationInfo.packageName
4345                                    .equals(ai.applicationInfo.packageName)) {
4346                                continue;
4347                            }
4348                            if (!ri.activityInfo.name.equals(ai.name)) {
4349                                continue;
4350                            }
4351
4352                            if (removeMatches) {
4353                                pir.removeFilter(pa);
4354                                changed = true;
4355                                if (DEBUG_PREFERRED) {
4356                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4357                                }
4358                                break;
4359                            }
4360
4361                            // Okay we found a previously set preferred or last chosen app.
4362                            // If the result set is different from when this
4363                            // was created, we need to clear it and re-ask the
4364                            // user their preference, if we're looking for an "always" type entry.
4365                            if (always && !pa.mPref.sameSet(query)) {
4366                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4367                                        + intent + " type " + resolvedType);
4368                                if (DEBUG_PREFERRED) {
4369                                    Slog.v(TAG, "Removing preferred activity since set changed "
4370                                            + pa.mPref.mComponent);
4371                                }
4372                                pir.removeFilter(pa);
4373                                // Re-add the filter as a "last chosen" entry (!always)
4374                                PreferredActivity lastChosen = new PreferredActivity(
4375                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4376                                pir.addFilter(lastChosen);
4377                                changed = true;
4378                                return null;
4379                            }
4380
4381                            // Yay! Either the set matched or we're looking for the last chosen
4382                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4383                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4384                            return ri;
4385                        }
4386                    }
4387                } finally {
4388                    if (changed) {
4389                        if (DEBUG_PREFERRED) {
4390                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4391                        }
4392                        scheduleWritePackageRestrictionsLocked(userId);
4393                    }
4394                }
4395            }
4396        }
4397        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4398        return null;
4399    }
4400
4401    /*
4402     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4403     */
4404    @Override
4405    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4406            int targetUserId) {
4407        mContext.enforceCallingOrSelfPermission(
4408                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4409        List<CrossProfileIntentFilter> matches =
4410                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4411        if (matches != null) {
4412            int size = matches.size();
4413            for (int i = 0; i < size; i++) {
4414                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4415            }
4416        }
4417        if (hasWebURI(intent)) {
4418            // cross-profile app linking works only towards the parent.
4419            final UserInfo parent = getProfileParent(sourceUserId);
4420            synchronized(mPackages) {
4421                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4422                        intent, resolvedType, 0, sourceUserId, parent.id);
4423                return xpDomainInfo != null
4424                        && xpDomainInfo.bestDomainVerificationStatus !=
4425                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4426            }
4427        }
4428        return false;
4429    }
4430
4431    private UserInfo getProfileParent(int userId) {
4432        final long identity = Binder.clearCallingIdentity();
4433        try {
4434            return sUserManager.getProfileParent(userId);
4435        } finally {
4436            Binder.restoreCallingIdentity(identity);
4437        }
4438    }
4439
4440    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4441            String resolvedType, int userId) {
4442        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4443        if (resolver != null) {
4444            return resolver.queryIntent(intent, resolvedType, false, userId);
4445        }
4446        return null;
4447    }
4448
4449    @Override
4450    public List<ResolveInfo> queryIntentActivities(Intent intent,
4451            String resolvedType, int flags, int userId) {
4452        if (!sUserManager.exists(userId)) return Collections.emptyList();
4453        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4454        ComponentName comp = intent.getComponent();
4455        if (comp == null) {
4456            if (intent.getSelector() != null) {
4457                intent = intent.getSelector();
4458                comp = intent.getComponent();
4459            }
4460        }
4461
4462        if (comp != null) {
4463            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4464            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4465            if (ai != null) {
4466                final ResolveInfo ri = new ResolveInfo();
4467                ri.activityInfo = ai;
4468                list.add(ri);
4469            }
4470            return list;
4471        }
4472
4473        // reader
4474        synchronized (mPackages) {
4475            final String pkgName = intent.getPackage();
4476            if (pkgName == null) {
4477                List<CrossProfileIntentFilter> matchingFilters =
4478                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4479                // Check for results that need to skip the current profile.
4480                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4481                        resolvedType, flags, userId);
4482                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4483                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4484                    result.add(xpResolveInfo);
4485                    return filterIfNotPrimaryUser(result, userId);
4486                }
4487
4488                // Check for results in the current profile.
4489                List<ResolveInfo> result = mActivities.queryIntent(
4490                        intent, resolvedType, flags, userId);
4491
4492                // Check for cross profile results.
4493                xpResolveInfo = queryCrossProfileIntents(
4494                        matchingFilters, intent, resolvedType, flags, userId);
4495                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4496                    result.add(xpResolveInfo);
4497                    Collections.sort(result, mResolvePrioritySorter);
4498                }
4499                result = filterIfNotPrimaryUser(result, userId);
4500                if (hasWebURI(intent)) {
4501                    CrossProfileDomainInfo xpDomainInfo = null;
4502                    final UserInfo parent = getProfileParent(userId);
4503                    if (parent != null) {
4504                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4505                                flags, userId, parent.id);
4506                    }
4507                    if (xpDomainInfo != null) {
4508                        if (xpResolveInfo != null) {
4509                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4510                            // in the result.
4511                            result.remove(xpResolveInfo);
4512                        }
4513                        if (result.size() == 0) {
4514                            result.add(xpDomainInfo.resolveInfo);
4515                            return result;
4516                        }
4517                    } else if (result.size() <= 1) {
4518                        return result;
4519                    }
4520                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4521                            xpDomainInfo, userId);
4522                    Collections.sort(result, mResolvePrioritySorter);
4523                }
4524                return result;
4525            }
4526            final PackageParser.Package pkg = mPackages.get(pkgName);
4527            if (pkg != null) {
4528                return filterIfNotPrimaryUser(
4529                        mActivities.queryIntentForPackage(
4530                                intent, resolvedType, flags, pkg.activities, userId),
4531                        userId);
4532            }
4533            return new ArrayList<ResolveInfo>();
4534        }
4535    }
4536
4537    private static class CrossProfileDomainInfo {
4538        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4539        ResolveInfo resolveInfo;
4540        /* Best domain verification status of the activities found in the other profile */
4541        int bestDomainVerificationStatus;
4542    }
4543
4544    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4545            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4546        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4547                sourceUserId)) {
4548            return null;
4549        }
4550        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4551                resolvedType, flags, parentUserId);
4552
4553        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4554            return null;
4555        }
4556        CrossProfileDomainInfo result = null;
4557        int size = resultTargetUser.size();
4558        for (int i = 0; i < size; i++) {
4559            ResolveInfo riTargetUser = resultTargetUser.get(i);
4560            // Intent filter verification is only for filters that specify a host. So don't return
4561            // those that handle all web uris.
4562            if (riTargetUser.handleAllWebDataURI) {
4563                continue;
4564            }
4565            String packageName = riTargetUser.activityInfo.packageName;
4566            PackageSetting ps = mSettings.mPackages.get(packageName);
4567            if (ps == null) {
4568                continue;
4569            }
4570            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4571            if (result == null) {
4572                result = new CrossProfileDomainInfo();
4573                result.resolveInfo =
4574                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4575                result.bestDomainVerificationStatus = status;
4576            } else {
4577                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4578                        result.bestDomainVerificationStatus);
4579            }
4580        }
4581        return result;
4582    }
4583
4584    /**
4585     * Verification statuses are ordered from the worse to the best, except for
4586     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4587     */
4588    private int bestDomainVerificationStatus(int status1, int status2) {
4589        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4590            return status2;
4591        }
4592        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4593            return status1;
4594        }
4595        return (int) MathUtils.max(status1, status2);
4596    }
4597
4598    private boolean isUserEnabled(int userId) {
4599        long callingId = Binder.clearCallingIdentity();
4600        try {
4601            UserInfo userInfo = sUserManager.getUserInfo(userId);
4602            return userInfo != null && userInfo.isEnabled();
4603        } finally {
4604            Binder.restoreCallingIdentity(callingId);
4605        }
4606    }
4607
4608    /**
4609     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4610     *
4611     * @return filtered list
4612     */
4613    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4614        if (userId == UserHandle.USER_OWNER) {
4615            return resolveInfos;
4616        }
4617        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4618            ResolveInfo info = resolveInfos.get(i);
4619            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4620                resolveInfos.remove(i);
4621            }
4622        }
4623        return resolveInfos;
4624    }
4625
4626    private static boolean hasWebURI(Intent intent) {
4627        if (intent.getData() == null) {
4628            return false;
4629        }
4630        final String scheme = intent.getScheme();
4631        if (TextUtils.isEmpty(scheme)) {
4632            return false;
4633        }
4634        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4635    }
4636
4637    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4638            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4639            int userId) {
4640        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4641            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4642                    candidates.size());
4643        }
4644
4645        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4646        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4647        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4648        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4649        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4650
4651        synchronized (mPackages) {
4652            final int count = candidates.size();
4653            // First, try to use linked apps. Partition the candidates into four lists:
4654            // one for the final results, one for the "do not use ever", one for "undefined status"
4655            // and finally one for "browser app type".
4656            for (int n=0; n<count; n++) {
4657                ResolveInfo info = candidates.get(n);
4658                String packageName = info.activityInfo.packageName;
4659                PackageSetting ps = mSettings.mPackages.get(packageName);
4660                if (ps != null) {
4661                    // Add to the special match all list (Browser use case)
4662                    if (info.handleAllWebDataURI) {
4663                        matchAllList.add(info);
4664                        continue;
4665                    }
4666                    // Try to get the status from User settings first
4667                    int status = getDomainVerificationStatusLPr(ps, userId);
4668                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4669                        if (DEBUG_DOMAIN_VERIFICATION) {
4670                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4671                        }
4672                        alwaysList.add(info);
4673                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4674                        if (DEBUG_DOMAIN_VERIFICATION) {
4675                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4676                        }
4677                        neverList.add(info);
4678                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4679                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4680                        if (DEBUG_DOMAIN_VERIFICATION) {
4681                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4682                        }
4683                        undefinedList.add(info);
4684                    }
4685                }
4686            }
4687            // First try to add the "always" resolution for the current user if there is any
4688            if (alwaysList.size() > 0) {
4689                result.addAll(alwaysList);
4690            // if there is an "always" for the parent user, add it.
4691            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4692                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4693                result.add(xpDomainInfo.resolveInfo);
4694            } else {
4695                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4696                result.addAll(undefinedList);
4697                if (xpDomainInfo != null && (
4698                        xpDomainInfo.bestDomainVerificationStatus
4699                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4700                        || xpDomainInfo.bestDomainVerificationStatus
4701                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4702                    result.add(xpDomainInfo.resolveInfo);
4703                }
4704                // Also add Browsers (all of them or only the default one)
4705                if ((flags & MATCH_ALL) != 0) {
4706                    result.addAll(matchAllList);
4707                } else {
4708                    // Try to add the Default Browser if we can
4709                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4710                            UserHandle.myUserId());
4711                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4712                        boolean defaultBrowserFound = false;
4713                        final int browserCount = matchAllList.size();
4714                        for (int n=0; n<browserCount; n++) {
4715                            ResolveInfo browser = matchAllList.get(n);
4716                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4717                                result.add(browser);
4718                                defaultBrowserFound = true;
4719                                break;
4720                            }
4721                        }
4722                        if (!defaultBrowserFound) {
4723                            result.addAll(matchAllList);
4724                        }
4725                    } else {
4726                        result.addAll(matchAllList);
4727                    }
4728                }
4729
4730                // If there is nothing selected, add all candidates and remove the ones that the user
4731                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4732                if (result.size() == 0) {
4733                    result.addAll(candidates);
4734                    result.removeAll(neverList);
4735                }
4736            }
4737        }
4738        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4739            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4740                    result.size());
4741            for (ResolveInfo info : result) {
4742                Slog.v(TAG, "  + " + info.activityInfo);
4743            }
4744        }
4745        return result;
4746    }
4747
4748    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4749        int status = ps.getDomainVerificationStatusForUser(userId);
4750        // if none available, get the master status
4751        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4752            if (ps.getIntentFilterVerificationInfo() != null) {
4753                status = ps.getIntentFilterVerificationInfo().getStatus();
4754            }
4755        }
4756        return status;
4757    }
4758
4759    private ResolveInfo querySkipCurrentProfileIntents(
4760            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4761            int flags, int sourceUserId) {
4762        if (matchingFilters != null) {
4763            int size = matchingFilters.size();
4764            for (int i = 0; i < size; i ++) {
4765                CrossProfileIntentFilter filter = matchingFilters.get(i);
4766                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4767                    // Checking if there are activities in the target user that can handle the
4768                    // intent.
4769                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4770                            flags, sourceUserId);
4771                    if (resolveInfo != null) {
4772                        return resolveInfo;
4773                    }
4774                }
4775            }
4776        }
4777        return null;
4778    }
4779
4780    // Return matching ResolveInfo if any for skip current profile intent filters.
4781    private ResolveInfo queryCrossProfileIntents(
4782            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4783            int flags, int sourceUserId) {
4784        if (matchingFilters != null) {
4785            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4786            // match the same intent. For performance reasons, it is better not to
4787            // run queryIntent twice for the same userId
4788            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4789            int size = matchingFilters.size();
4790            for (int i = 0; i < size; i++) {
4791                CrossProfileIntentFilter filter = matchingFilters.get(i);
4792                int targetUserId = filter.getTargetUserId();
4793                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4794                        && !alreadyTriedUserIds.get(targetUserId)) {
4795                    // Checking if there are activities in the target user that can handle the
4796                    // intent.
4797                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4798                            flags, sourceUserId);
4799                    if (resolveInfo != null) return resolveInfo;
4800                    alreadyTriedUserIds.put(targetUserId, true);
4801                }
4802            }
4803        }
4804        return null;
4805    }
4806
4807    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4808            String resolvedType, int flags, int sourceUserId) {
4809        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4810                resolvedType, flags, filter.getTargetUserId());
4811        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4812            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4813        }
4814        return null;
4815    }
4816
4817    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4818            int sourceUserId, int targetUserId) {
4819        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4820        String className;
4821        if (targetUserId == UserHandle.USER_OWNER) {
4822            className = FORWARD_INTENT_TO_USER_OWNER;
4823        } else {
4824            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4825        }
4826        ComponentName forwardingActivityComponentName = new ComponentName(
4827                mAndroidApplication.packageName, className);
4828        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4829                sourceUserId);
4830        if (targetUserId == UserHandle.USER_OWNER) {
4831            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4832            forwardingResolveInfo.noResourceId = true;
4833        }
4834        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4835        forwardingResolveInfo.priority = 0;
4836        forwardingResolveInfo.preferredOrder = 0;
4837        forwardingResolveInfo.match = 0;
4838        forwardingResolveInfo.isDefault = true;
4839        forwardingResolveInfo.filter = filter;
4840        forwardingResolveInfo.targetUserId = targetUserId;
4841        return forwardingResolveInfo;
4842    }
4843
4844    @Override
4845    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4846            Intent[] specifics, String[] specificTypes, Intent intent,
4847            String resolvedType, int flags, int userId) {
4848        if (!sUserManager.exists(userId)) return Collections.emptyList();
4849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4850                false, "query intent activity options");
4851        final String resultsAction = intent.getAction();
4852
4853        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4854                | PackageManager.GET_RESOLVED_FILTER, userId);
4855
4856        if (DEBUG_INTENT_MATCHING) {
4857            Log.v(TAG, "Query " + intent + ": " + results);
4858        }
4859
4860        int specificsPos = 0;
4861        int N;
4862
4863        // todo: note that the algorithm used here is O(N^2).  This
4864        // isn't a problem in our current environment, but if we start running
4865        // into situations where we have more than 5 or 10 matches then this
4866        // should probably be changed to something smarter...
4867
4868        // First we go through and resolve each of the specific items
4869        // that were supplied, taking care of removing any corresponding
4870        // duplicate items in the generic resolve list.
4871        if (specifics != null) {
4872            for (int i=0; i<specifics.length; i++) {
4873                final Intent sintent = specifics[i];
4874                if (sintent == null) {
4875                    continue;
4876                }
4877
4878                if (DEBUG_INTENT_MATCHING) {
4879                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4880                }
4881
4882                String action = sintent.getAction();
4883                if (resultsAction != null && resultsAction.equals(action)) {
4884                    // If this action was explicitly requested, then don't
4885                    // remove things that have it.
4886                    action = null;
4887                }
4888
4889                ResolveInfo ri = null;
4890                ActivityInfo ai = null;
4891
4892                ComponentName comp = sintent.getComponent();
4893                if (comp == null) {
4894                    ri = resolveIntent(
4895                        sintent,
4896                        specificTypes != null ? specificTypes[i] : null,
4897                            flags, userId);
4898                    if (ri == null) {
4899                        continue;
4900                    }
4901                    if (ri == mResolveInfo) {
4902                        // ACK!  Must do something better with this.
4903                    }
4904                    ai = ri.activityInfo;
4905                    comp = new ComponentName(ai.applicationInfo.packageName,
4906                            ai.name);
4907                } else {
4908                    ai = getActivityInfo(comp, flags, userId);
4909                    if (ai == null) {
4910                        continue;
4911                    }
4912                }
4913
4914                // Look for any generic query activities that are duplicates
4915                // of this specific one, and remove them from the results.
4916                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4917                N = results.size();
4918                int j;
4919                for (j=specificsPos; j<N; j++) {
4920                    ResolveInfo sri = results.get(j);
4921                    if ((sri.activityInfo.name.equals(comp.getClassName())
4922                            && sri.activityInfo.applicationInfo.packageName.equals(
4923                                    comp.getPackageName()))
4924                        || (action != null && sri.filter.matchAction(action))) {
4925                        results.remove(j);
4926                        if (DEBUG_INTENT_MATCHING) Log.v(
4927                            TAG, "Removing duplicate item from " + j
4928                            + " due to specific " + specificsPos);
4929                        if (ri == null) {
4930                            ri = sri;
4931                        }
4932                        j--;
4933                        N--;
4934                    }
4935                }
4936
4937                // Add this specific item to its proper place.
4938                if (ri == null) {
4939                    ri = new ResolveInfo();
4940                    ri.activityInfo = ai;
4941                }
4942                results.add(specificsPos, ri);
4943                ri.specificIndex = i;
4944                specificsPos++;
4945            }
4946        }
4947
4948        // Now we go through the remaining generic results and remove any
4949        // duplicate actions that are found here.
4950        N = results.size();
4951        for (int i=specificsPos; i<N-1; i++) {
4952            final ResolveInfo rii = results.get(i);
4953            if (rii.filter == null) {
4954                continue;
4955            }
4956
4957            // Iterate over all of the actions of this result's intent
4958            // filter...  typically this should be just one.
4959            final Iterator<String> it = rii.filter.actionsIterator();
4960            if (it == null) {
4961                continue;
4962            }
4963            while (it.hasNext()) {
4964                final String action = it.next();
4965                if (resultsAction != null && resultsAction.equals(action)) {
4966                    // If this action was explicitly requested, then don't
4967                    // remove things that have it.
4968                    continue;
4969                }
4970                for (int j=i+1; j<N; j++) {
4971                    final ResolveInfo rij = results.get(j);
4972                    if (rij.filter != null && rij.filter.hasAction(action)) {
4973                        results.remove(j);
4974                        if (DEBUG_INTENT_MATCHING) Log.v(
4975                            TAG, "Removing duplicate item from " + j
4976                            + " due to action " + action + " at " + i);
4977                        j--;
4978                        N--;
4979                    }
4980                }
4981            }
4982
4983            // If the caller didn't request filter information, drop it now
4984            // so we don't have to marshall/unmarshall it.
4985            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4986                rii.filter = null;
4987            }
4988        }
4989
4990        // Filter out the caller activity if so requested.
4991        if (caller != null) {
4992            N = results.size();
4993            for (int i=0; i<N; i++) {
4994                ActivityInfo ainfo = results.get(i).activityInfo;
4995                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4996                        && caller.getClassName().equals(ainfo.name)) {
4997                    results.remove(i);
4998                    break;
4999                }
5000            }
5001        }
5002
5003        // If the caller didn't request filter information,
5004        // drop them now so we don't have to
5005        // marshall/unmarshall it.
5006        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5007            N = results.size();
5008            for (int i=0; i<N; i++) {
5009                results.get(i).filter = null;
5010            }
5011        }
5012
5013        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5014        return results;
5015    }
5016
5017    @Override
5018    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5019            int userId) {
5020        if (!sUserManager.exists(userId)) return Collections.emptyList();
5021        ComponentName comp = intent.getComponent();
5022        if (comp == null) {
5023            if (intent.getSelector() != null) {
5024                intent = intent.getSelector();
5025                comp = intent.getComponent();
5026            }
5027        }
5028        if (comp != null) {
5029            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5030            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5031            if (ai != null) {
5032                ResolveInfo ri = new ResolveInfo();
5033                ri.activityInfo = ai;
5034                list.add(ri);
5035            }
5036            return list;
5037        }
5038
5039        // reader
5040        synchronized (mPackages) {
5041            String pkgName = intent.getPackage();
5042            if (pkgName == null) {
5043                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5044            }
5045            final PackageParser.Package pkg = mPackages.get(pkgName);
5046            if (pkg != null) {
5047                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5048                        userId);
5049            }
5050            return null;
5051        }
5052    }
5053
5054    @Override
5055    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5056        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5057        if (!sUserManager.exists(userId)) return null;
5058        if (query != null) {
5059            if (query.size() >= 1) {
5060                // If there is more than one service with the same priority,
5061                // just arbitrarily pick the first one.
5062                return query.get(0);
5063            }
5064        }
5065        return null;
5066    }
5067
5068    @Override
5069    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5070            int userId) {
5071        if (!sUserManager.exists(userId)) return Collections.emptyList();
5072        ComponentName comp = intent.getComponent();
5073        if (comp == null) {
5074            if (intent.getSelector() != null) {
5075                intent = intent.getSelector();
5076                comp = intent.getComponent();
5077            }
5078        }
5079        if (comp != null) {
5080            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5081            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5082            if (si != null) {
5083                final ResolveInfo ri = new ResolveInfo();
5084                ri.serviceInfo = si;
5085                list.add(ri);
5086            }
5087            return list;
5088        }
5089
5090        // reader
5091        synchronized (mPackages) {
5092            String pkgName = intent.getPackage();
5093            if (pkgName == null) {
5094                return mServices.queryIntent(intent, resolvedType, flags, userId);
5095            }
5096            final PackageParser.Package pkg = mPackages.get(pkgName);
5097            if (pkg != null) {
5098                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5099                        userId);
5100            }
5101            return null;
5102        }
5103    }
5104
5105    @Override
5106    public List<ResolveInfo> queryIntentContentProviders(
5107            Intent intent, String resolvedType, int flags, int userId) {
5108        if (!sUserManager.exists(userId)) return Collections.emptyList();
5109        ComponentName comp = intent.getComponent();
5110        if (comp == null) {
5111            if (intent.getSelector() != null) {
5112                intent = intent.getSelector();
5113                comp = intent.getComponent();
5114            }
5115        }
5116        if (comp != null) {
5117            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5118            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5119            if (pi != null) {
5120                final ResolveInfo ri = new ResolveInfo();
5121                ri.providerInfo = pi;
5122                list.add(ri);
5123            }
5124            return list;
5125        }
5126
5127        // reader
5128        synchronized (mPackages) {
5129            String pkgName = intent.getPackage();
5130            if (pkgName == null) {
5131                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5132            }
5133            final PackageParser.Package pkg = mPackages.get(pkgName);
5134            if (pkg != null) {
5135                return mProviders.queryIntentForPackage(
5136                        intent, resolvedType, flags, pkg.providers, userId);
5137            }
5138            return null;
5139        }
5140    }
5141
5142    @Override
5143    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5144        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5145
5146        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5147
5148        // writer
5149        synchronized (mPackages) {
5150            ArrayList<PackageInfo> list;
5151            if (listUninstalled) {
5152                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5153                for (PackageSetting ps : mSettings.mPackages.values()) {
5154                    PackageInfo pi;
5155                    if (ps.pkg != null) {
5156                        pi = generatePackageInfo(ps.pkg, flags, userId);
5157                    } else {
5158                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5159                    }
5160                    if (pi != null) {
5161                        list.add(pi);
5162                    }
5163                }
5164            } else {
5165                list = new ArrayList<PackageInfo>(mPackages.size());
5166                for (PackageParser.Package p : mPackages.values()) {
5167                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5168                    if (pi != null) {
5169                        list.add(pi);
5170                    }
5171                }
5172            }
5173
5174            return new ParceledListSlice<PackageInfo>(list);
5175        }
5176    }
5177
5178    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5179            String[] permissions, boolean[] tmp, int flags, int userId) {
5180        int numMatch = 0;
5181        final PermissionsState permissionsState = ps.getPermissionsState();
5182        for (int i=0; i<permissions.length; i++) {
5183            final String permission = permissions[i];
5184            if (permissionsState.hasPermission(permission, userId)) {
5185                tmp[i] = true;
5186                numMatch++;
5187            } else {
5188                tmp[i] = false;
5189            }
5190        }
5191        if (numMatch == 0) {
5192            return;
5193        }
5194        PackageInfo pi;
5195        if (ps.pkg != null) {
5196            pi = generatePackageInfo(ps.pkg, flags, userId);
5197        } else {
5198            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5199        }
5200        // The above might return null in cases of uninstalled apps or install-state
5201        // skew across users/profiles.
5202        if (pi != null) {
5203            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5204                if (numMatch == permissions.length) {
5205                    pi.requestedPermissions = permissions;
5206                } else {
5207                    pi.requestedPermissions = new String[numMatch];
5208                    numMatch = 0;
5209                    for (int i=0; i<permissions.length; i++) {
5210                        if (tmp[i]) {
5211                            pi.requestedPermissions[numMatch] = permissions[i];
5212                            numMatch++;
5213                        }
5214                    }
5215                }
5216            }
5217            list.add(pi);
5218        }
5219    }
5220
5221    @Override
5222    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5223            String[] permissions, int flags, int userId) {
5224        if (!sUserManager.exists(userId)) return null;
5225        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5226
5227        // writer
5228        synchronized (mPackages) {
5229            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5230            boolean[] tmpBools = new boolean[permissions.length];
5231            if (listUninstalled) {
5232                for (PackageSetting ps : mSettings.mPackages.values()) {
5233                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5234                }
5235            } else {
5236                for (PackageParser.Package pkg : mPackages.values()) {
5237                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5238                    if (ps != null) {
5239                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5240                                userId);
5241                    }
5242                }
5243            }
5244
5245            return new ParceledListSlice<PackageInfo>(list);
5246        }
5247    }
5248
5249    @Override
5250    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5251        if (!sUserManager.exists(userId)) return null;
5252        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5253
5254        // writer
5255        synchronized (mPackages) {
5256            ArrayList<ApplicationInfo> list;
5257            if (listUninstalled) {
5258                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5259                for (PackageSetting ps : mSettings.mPackages.values()) {
5260                    ApplicationInfo ai;
5261                    if (ps.pkg != null) {
5262                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5263                                ps.readUserState(userId), userId);
5264                    } else {
5265                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5266                    }
5267                    if (ai != null) {
5268                        list.add(ai);
5269                    }
5270                }
5271            } else {
5272                list = new ArrayList<ApplicationInfo>(mPackages.size());
5273                for (PackageParser.Package p : mPackages.values()) {
5274                    if (p.mExtras != null) {
5275                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5276                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5277                        if (ai != null) {
5278                            list.add(ai);
5279                        }
5280                    }
5281                }
5282            }
5283
5284            return new ParceledListSlice<ApplicationInfo>(list);
5285        }
5286    }
5287
5288    public List<ApplicationInfo> getPersistentApplications(int flags) {
5289        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5290
5291        // reader
5292        synchronized (mPackages) {
5293            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5294            final int userId = UserHandle.getCallingUserId();
5295            while (i.hasNext()) {
5296                final PackageParser.Package p = i.next();
5297                if (p.applicationInfo != null
5298                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5299                        && (!mSafeMode || isSystemApp(p))) {
5300                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5301                    if (ps != null) {
5302                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5303                                ps.readUserState(userId), userId);
5304                        if (ai != null) {
5305                            finalList.add(ai);
5306                        }
5307                    }
5308                }
5309            }
5310        }
5311
5312        return finalList;
5313    }
5314
5315    @Override
5316    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5317        if (!sUserManager.exists(userId)) return null;
5318        // reader
5319        synchronized (mPackages) {
5320            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5321            PackageSetting ps = provider != null
5322                    ? mSettings.mPackages.get(provider.owner.packageName)
5323                    : null;
5324            return ps != null
5325                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5326                    && (!mSafeMode || (provider.info.applicationInfo.flags
5327                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5328                    ? PackageParser.generateProviderInfo(provider, flags,
5329                            ps.readUserState(userId), userId)
5330                    : null;
5331        }
5332    }
5333
5334    /**
5335     * @deprecated
5336     */
5337    @Deprecated
5338    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5339        // reader
5340        synchronized (mPackages) {
5341            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5342                    .entrySet().iterator();
5343            final int userId = UserHandle.getCallingUserId();
5344            while (i.hasNext()) {
5345                Map.Entry<String, PackageParser.Provider> entry = i.next();
5346                PackageParser.Provider p = entry.getValue();
5347                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5348
5349                if (ps != null && p.syncable
5350                        && (!mSafeMode || (p.info.applicationInfo.flags
5351                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5352                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5353                            ps.readUserState(userId), userId);
5354                    if (info != null) {
5355                        outNames.add(entry.getKey());
5356                        outInfo.add(info);
5357                    }
5358                }
5359            }
5360        }
5361    }
5362
5363    @Override
5364    public List<ProviderInfo> queryContentProviders(String processName,
5365            int uid, int flags) {
5366        ArrayList<ProviderInfo> finalList = null;
5367        // reader
5368        synchronized (mPackages) {
5369            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5370            final int userId = processName != null ?
5371                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5372            while (i.hasNext()) {
5373                final PackageParser.Provider p = i.next();
5374                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5375                if (ps != null && p.info.authority != null
5376                        && (processName == null
5377                                || (p.info.processName.equals(processName)
5378                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5379                        && mSettings.isEnabledLPr(p.info, flags, userId)
5380                        && (!mSafeMode
5381                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5382                    if (finalList == null) {
5383                        finalList = new ArrayList<ProviderInfo>(3);
5384                    }
5385                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5386                            ps.readUserState(userId), userId);
5387                    if (info != null) {
5388                        finalList.add(info);
5389                    }
5390                }
5391            }
5392        }
5393
5394        if (finalList != null) {
5395            Collections.sort(finalList, mProviderInitOrderSorter);
5396        }
5397
5398        return finalList;
5399    }
5400
5401    @Override
5402    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5403            int flags) {
5404        // reader
5405        synchronized (mPackages) {
5406            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5407            return PackageParser.generateInstrumentationInfo(i, flags);
5408        }
5409    }
5410
5411    @Override
5412    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5413            int flags) {
5414        ArrayList<InstrumentationInfo> finalList =
5415            new ArrayList<InstrumentationInfo>();
5416
5417        // reader
5418        synchronized (mPackages) {
5419            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5420            while (i.hasNext()) {
5421                final PackageParser.Instrumentation p = i.next();
5422                if (targetPackage == null
5423                        || targetPackage.equals(p.info.targetPackage)) {
5424                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5425                            flags);
5426                    if (ii != null) {
5427                        finalList.add(ii);
5428                    }
5429                }
5430            }
5431        }
5432
5433        return finalList;
5434    }
5435
5436    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5437        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5438        if (overlays == null) {
5439            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5440            return;
5441        }
5442        for (PackageParser.Package opkg : overlays.values()) {
5443            // Not much to do if idmap fails: we already logged the error
5444            // and we certainly don't want to abort installation of pkg simply
5445            // because an overlay didn't fit properly. For these reasons,
5446            // ignore the return value of createIdmapForPackagePairLI.
5447            createIdmapForPackagePairLI(pkg, opkg);
5448        }
5449    }
5450
5451    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5452            PackageParser.Package opkg) {
5453        if (!opkg.mTrustedOverlay) {
5454            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5455                    opkg.baseCodePath + ": overlay not trusted");
5456            return false;
5457        }
5458        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5459        if (overlaySet == null) {
5460            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5461                    opkg.baseCodePath + " but target package has no known overlays");
5462            return false;
5463        }
5464        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5465        // TODO: generate idmap for split APKs
5466        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5467            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5468                    + opkg.baseCodePath);
5469            return false;
5470        }
5471        PackageParser.Package[] overlayArray =
5472            overlaySet.values().toArray(new PackageParser.Package[0]);
5473        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5474            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5475                return p1.mOverlayPriority - p2.mOverlayPriority;
5476            }
5477        };
5478        Arrays.sort(overlayArray, cmp);
5479
5480        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5481        int i = 0;
5482        for (PackageParser.Package p : overlayArray) {
5483            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5484        }
5485        return true;
5486    }
5487
5488    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5489        final File[] files = dir.listFiles();
5490        if (ArrayUtils.isEmpty(files)) {
5491            Log.d(TAG, "No files in app dir " + dir);
5492            return;
5493        }
5494
5495        if (DEBUG_PACKAGE_SCANNING) {
5496            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5497                    + " flags=0x" + Integer.toHexString(parseFlags));
5498        }
5499
5500        for (File file : files) {
5501            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5502                    && !PackageInstallerService.isStageName(file.getName());
5503            if (!isPackage) {
5504                // Ignore entries which are not packages
5505                continue;
5506            }
5507            try {
5508                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5509                        scanFlags, currentTime, null);
5510            } catch (PackageManagerException e) {
5511                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5512
5513                // Delete invalid userdata apps
5514                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5515                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5516                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5517                    if (file.isDirectory()) {
5518                        mInstaller.rmPackageDir(file.getAbsolutePath());
5519                    } else {
5520                        file.delete();
5521                    }
5522                }
5523            }
5524        }
5525    }
5526
5527    private static File getSettingsProblemFile() {
5528        File dataDir = Environment.getDataDirectory();
5529        File systemDir = new File(dataDir, "system");
5530        File fname = new File(systemDir, "uiderrors.txt");
5531        return fname;
5532    }
5533
5534    static void reportSettingsProblem(int priority, String msg) {
5535        logCriticalInfo(priority, msg);
5536    }
5537
5538    static void logCriticalInfo(int priority, String msg) {
5539        Slog.println(priority, TAG, msg);
5540        EventLogTags.writePmCriticalInfo(msg);
5541        try {
5542            File fname = getSettingsProblemFile();
5543            FileOutputStream out = new FileOutputStream(fname, true);
5544            PrintWriter pw = new FastPrintWriter(out);
5545            SimpleDateFormat formatter = new SimpleDateFormat();
5546            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5547            pw.println(dateString + ": " + msg);
5548            pw.close();
5549            FileUtils.setPermissions(
5550                    fname.toString(),
5551                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5552                    -1, -1);
5553        } catch (java.io.IOException e) {
5554        }
5555    }
5556
5557    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5558            PackageParser.Package pkg, File srcFile, int parseFlags)
5559            throws PackageManagerException {
5560        if (ps != null
5561                && ps.codePath.equals(srcFile)
5562                && ps.timeStamp == srcFile.lastModified()
5563                && !isCompatSignatureUpdateNeeded(pkg)
5564                && !isRecoverSignatureUpdateNeeded(pkg)) {
5565            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5566            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5567            ArraySet<PublicKey> signingKs;
5568            synchronized (mPackages) {
5569                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5570            }
5571            if (ps.signatures.mSignatures != null
5572                    && ps.signatures.mSignatures.length != 0
5573                    && signingKs != null) {
5574                // Optimization: reuse the existing cached certificates
5575                // if the package appears to be unchanged.
5576                pkg.mSignatures = ps.signatures.mSignatures;
5577                pkg.mSigningKeys = signingKs;
5578                return;
5579            }
5580
5581            Slog.w(TAG, "PackageSetting for " + ps.name
5582                    + " is missing signatures.  Collecting certs again to recover them.");
5583        } else {
5584            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5585        }
5586
5587        try {
5588            pp.collectCertificates(pkg, parseFlags);
5589            pp.collectManifestDigest(pkg);
5590        } catch (PackageParserException e) {
5591            throw PackageManagerException.from(e);
5592        }
5593    }
5594
5595    /*
5596     *  Scan a package and return the newly parsed package.
5597     *  Returns null in case of errors and the error code is stored in mLastScanError
5598     */
5599    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5600            long currentTime, UserHandle user) throws PackageManagerException {
5601        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5602        parseFlags |= mDefParseFlags;
5603        PackageParser pp = new PackageParser();
5604        pp.setSeparateProcesses(mSeparateProcesses);
5605        pp.setOnlyCoreApps(mOnlyCore);
5606        pp.setDisplayMetrics(mMetrics);
5607
5608        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5609            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5610        }
5611
5612        final PackageParser.Package pkg;
5613        try {
5614            pkg = pp.parsePackage(scanFile, parseFlags);
5615        } catch (PackageParserException e) {
5616            throw PackageManagerException.from(e);
5617        }
5618
5619        PackageSetting ps = null;
5620        PackageSetting updatedPkg;
5621        // reader
5622        synchronized (mPackages) {
5623            // Look to see if we already know about this package.
5624            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5625            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5626                // This package has been renamed to its original name.  Let's
5627                // use that.
5628                ps = mSettings.peekPackageLPr(oldName);
5629            }
5630            // If there was no original package, see one for the real package name.
5631            if (ps == null) {
5632                ps = mSettings.peekPackageLPr(pkg.packageName);
5633            }
5634            // Check to see if this package could be hiding/updating a system
5635            // package.  Must look for it either under the original or real
5636            // package name depending on our state.
5637            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5638            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5639        }
5640        boolean updatedPkgBetter = false;
5641        // First check if this is a system package that may involve an update
5642        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5643            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5644            // it needs to drop FLAG_PRIVILEGED.
5645            if (locationIsPrivileged(scanFile)) {
5646                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5647            } else {
5648                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5649            }
5650
5651            if (ps != null && !ps.codePath.equals(scanFile)) {
5652                // The path has changed from what was last scanned...  check the
5653                // version of the new path against what we have stored to determine
5654                // what to do.
5655                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5656                if (pkg.mVersionCode <= ps.versionCode) {
5657                    // The system package has been updated and the code path does not match
5658                    // Ignore entry. Skip it.
5659                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5660                            + " ignored: updated version " + ps.versionCode
5661                            + " better than this " + pkg.mVersionCode);
5662                    if (!updatedPkg.codePath.equals(scanFile)) {
5663                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5664                                + ps.name + " changing from " + updatedPkg.codePathString
5665                                + " to " + scanFile);
5666                        updatedPkg.codePath = scanFile;
5667                        updatedPkg.codePathString = scanFile.toString();
5668                        updatedPkg.resourcePath = scanFile;
5669                        updatedPkg.resourcePathString = scanFile.toString();
5670                    }
5671                    updatedPkg.pkg = pkg;
5672                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5673                            "Package " + ps.name + " at " + scanFile
5674                                    + " ignored: updated version " + ps.versionCode
5675                                    + " better than this " + pkg.mVersionCode);
5676                } else {
5677                    // The current app on the system partition is better than
5678                    // what we have updated to on the data partition; switch
5679                    // back to the system partition version.
5680                    // At this point, its safely assumed that package installation for
5681                    // apps in system partition will go through. If not there won't be a working
5682                    // version of the app
5683                    // writer
5684                    synchronized (mPackages) {
5685                        // Just remove the loaded entries from package lists.
5686                        mPackages.remove(ps.name);
5687                    }
5688
5689                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5690                            + " reverting from " + ps.codePathString
5691                            + ": new version " + pkg.mVersionCode
5692                            + " better than installed " + ps.versionCode);
5693
5694                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5695                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5696                    synchronized (mInstallLock) {
5697                        args.cleanUpResourcesLI();
5698                    }
5699                    synchronized (mPackages) {
5700                        mSettings.enableSystemPackageLPw(ps.name);
5701                    }
5702                    updatedPkgBetter = true;
5703                }
5704            }
5705        }
5706
5707        if (updatedPkg != null) {
5708            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5709            // initially
5710            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5711
5712            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5713            // flag set initially
5714            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5715                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5716            }
5717        }
5718
5719        // Verify certificates against what was last scanned
5720        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5721
5722        /*
5723         * A new system app appeared, but we already had a non-system one of the
5724         * same name installed earlier.
5725         */
5726        boolean shouldHideSystemApp = false;
5727        if (updatedPkg == null && ps != null
5728                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5729            /*
5730             * Check to make sure the signatures match first. If they don't,
5731             * wipe the installed application and its data.
5732             */
5733            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5734                    != PackageManager.SIGNATURE_MATCH) {
5735                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5736                        + " signatures don't match existing userdata copy; removing");
5737                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5738                ps = null;
5739            } else {
5740                /*
5741                 * If the newly-added system app is an older version than the
5742                 * already installed version, hide it. It will be scanned later
5743                 * and re-added like an update.
5744                 */
5745                if (pkg.mVersionCode <= ps.versionCode) {
5746                    shouldHideSystemApp = true;
5747                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5748                            + " but new version " + pkg.mVersionCode + " better than installed "
5749                            + ps.versionCode + "; hiding system");
5750                } else {
5751                    /*
5752                     * The newly found system app is a newer version that the
5753                     * one previously installed. Simply remove the
5754                     * already-installed application and replace it with our own
5755                     * while keeping the application data.
5756                     */
5757                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5758                            + " reverting from " + ps.codePathString + ": new version "
5759                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5760                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5761                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5762                    synchronized (mInstallLock) {
5763                        args.cleanUpResourcesLI();
5764                    }
5765                }
5766            }
5767        }
5768
5769        // The apk is forward locked (not public) if its code and resources
5770        // are kept in different files. (except for app in either system or
5771        // vendor path).
5772        // TODO grab this value from PackageSettings
5773        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5774            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5775                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5776            }
5777        }
5778
5779        // TODO: extend to support forward-locked splits
5780        String resourcePath = null;
5781        String baseResourcePath = null;
5782        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5783            if (ps != null && ps.resourcePathString != null) {
5784                resourcePath = ps.resourcePathString;
5785                baseResourcePath = ps.resourcePathString;
5786            } else {
5787                // Should not happen at all. Just log an error.
5788                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5789            }
5790        } else {
5791            resourcePath = pkg.codePath;
5792            baseResourcePath = pkg.baseCodePath;
5793        }
5794
5795        // Set application objects path explicitly.
5796        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5797        pkg.applicationInfo.setCodePath(pkg.codePath);
5798        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5799        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5800        pkg.applicationInfo.setResourcePath(resourcePath);
5801        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5802        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5803
5804        // Note that we invoke the following method only if we are about to unpack an application
5805        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5806                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5807
5808        /*
5809         * If the system app should be overridden by a previously installed
5810         * data, hide the system app now and let the /data/app scan pick it up
5811         * again.
5812         */
5813        if (shouldHideSystemApp) {
5814            synchronized (mPackages) {
5815                /*
5816                 * We have to grant systems permissions before we hide, because
5817                 * grantPermissions will assume the package update is trying to
5818                 * expand its permissions.
5819                 */
5820                grantPermissionsLPw(pkg, true, pkg.packageName);
5821                mSettings.disableSystemPackageLPw(pkg.packageName);
5822            }
5823        }
5824
5825        return scannedPkg;
5826    }
5827
5828    private static String fixProcessName(String defProcessName,
5829            String processName, int uid) {
5830        if (processName == null) {
5831            return defProcessName;
5832        }
5833        return processName;
5834    }
5835
5836    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5837            throws PackageManagerException {
5838        if (pkgSetting.signatures.mSignatures != null) {
5839            // Already existing package. Make sure signatures match
5840            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5841                    == PackageManager.SIGNATURE_MATCH;
5842            if (!match) {
5843                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5844                        == PackageManager.SIGNATURE_MATCH;
5845            }
5846            if (!match) {
5847                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5848                        == PackageManager.SIGNATURE_MATCH;
5849            }
5850            if (!match) {
5851                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5852                        + pkg.packageName + " signatures do not match the "
5853                        + "previously installed version; ignoring!");
5854            }
5855        }
5856
5857        // Check for shared user signatures
5858        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5859            // Already existing package. Make sure signatures match
5860            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5861                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5862            if (!match) {
5863                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5864                        == PackageManager.SIGNATURE_MATCH;
5865            }
5866            if (!match) {
5867                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5868                        == PackageManager.SIGNATURE_MATCH;
5869            }
5870            if (!match) {
5871                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5872                        "Package " + pkg.packageName
5873                        + " has no signatures that match those in shared user "
5874                        + pkgSetting.sharedUser.name + "; ignoring!");
5875            }
5876        }
5877    }
5878
5879    /**
5880     * Enforces that only the system UID or root's UID can call a method exposed
5881     * via Binder.
5882     *
5883     * @param message used as message if SecurityException is thrown
5884     * @throws SecurityException if the caller is not system or root
5885     */
5886    private static final void enforceSystemOrRoot(String message) {
5887        final int uid = Binder.getCallingUid();
5888        if (uid != Process.SYSTEM_UID && uid != 0) {
5889            throw new SecurityException(message);
5890        }
5891    }
5892
5893    @Override
5894    public void performBootDexOpt() {
5895        enforceSystemOrRoot("Only the system can request dexopt be performed");
5896
5897        // Before everything else, see whether we need to fstrim.
5898        try {
5899            IMountService ms = PackageHelper.getMountService();
5900            if (ms != null) {
5901                final boolean isUpgrade = isUpgrade();
5902                boolean doTrim = isUpgrade;
5903                if (doTrim) {
5904                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5905                } else {
5906                    final long interval = android.provider.Settings.Global.getLong(
5907                            mContext.getContentResolver(),
5908                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5909                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5910                    if (interval > 0) {
5911                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5912                        if (timeSinceLast > interval) {
5913                            doTrim = true;
5914                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5915                                    + "; running immediately");
5916                        }
5917                    }
5918                }
5919                if (doTrim) {
5920                    if (!isFirstBoot()) {
5921                        try {
5922                            ActivityManagerNative.getDefault().showBootMessage(
5923                                    mContext.getResources().getString(
5924                                            R.string.android_upgrading_fstrim), true);
5925                        } catch (RemoteException e) {
5926                        }
5927                    }
5928                    ms.runMaintenance();
5929                }
5930            } else {
5931                Slog.e(TAG, "Mount service unavailable!");
5932            }
5933        } catch (RemoteException e) {
5934            // Can't happen; MountService is local
5935        }
5936
5937        final ArraySet<PackageParser.Package> pkgs;
5938        synchronized (mPackages) {
5939            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5940        }
5941
5942        if (pkgs != null) {
5943            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5944            // in case the device runs out of space.
5945            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5946            // Give priority to core apps.
5947            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5948                PackageParser.Package pkg = it.next();
5949                if (pkg.coreApp) {
5950                    if (DEBUG_DEXOPT) {
5951                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5952                    }
5953                    sortedPkgs.add(pkg);
5954                    it.remove();
5955                }
5956            }
5957            // Give priority to system apps that listen for pre boot complete.
5958            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5959            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5960            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5961                PackageParser.Package pkg = it.next();
5962                if (pkgNames.contains(pkg.packageName)) {
5963                    if (DEBUG_DEXOPT) {
5964                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5965                    }
5966                    sortedPkgs.add(pkg);
5967                    it.remove();
5968                }
5969            }
5970            // Give priority to system apps.
5971            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5972                PackageParser.Package pkg = it.next();
5973                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5974                    if (DEBUG_DEXOPT) {
5975                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5976                    }
5977                    sortedPkgs.add(pkg);
5978                    it.remove();
5979                }
5980            }
5981            // Give priority to updated system apps.
5982            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5983                PackageParser.Package pkg = it.next();
5984                if (pkg.isUpdatedSystemApp()) {
5985                    if (DEBUG_DEXOPT) {
5986                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5987                    }
5988                    sortedPkgs.add(pkg);
5989                    it.remove();
5990                }
5991            }
5992            // Give priority to apps that listen for boot complete.
5993            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5994            pkgNames = getPackageNamesForIntent(intent);
5995            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5996                PackageParser.Package pkg = it.next();
5997                if (pkgNames.contains(pkg.packageName)) {
5998                    if (DEBUG_DEXOPT) {
5999                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6000                    }
6001                    sortedPkgs.add(pkg);
6002                    it.remove();
6003                }
6004            }
6005            // Filter out packages that aren't recently used.
6006            filterRecentlyUsedApps(pkgs);
6007            // Add all remaining apps.
6008            for (PackageParser.Package pkg : pkgs) {
6009                if (DEBUG_DEXOPT) {
6010                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6011                }
6012                sortedPkgs.add(pkg);
6013            }
6014
6015            // If we want to be lazy, filter everything that wasn't recently used.
6016            if (mLazyDexOpt) {
6017                filterRecentlyUsedApps(sortedPkgs);
6018            }
6019
6020            int i = 0;
6021            int total = sortedPkgs.size();
6022            File dataDir = Environment.getDataDirectory();
6023            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6024            if (lowThreshold == 0) {
6025                throw new IllegalStateException("Invalid low memory threshold");
6026            }
6027            for (PackageParser.Package pkg : sortedPkgs) {
6028                long usableSpace = dataDir.getUsableSpace();
6029                if (usableSpace < lowThreshold) {
6030                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6031                    break;
6032                }
6033                performBootDexOpt(pkg, ++i, total);
6034            }
6035        }
6036    }
6037
6038    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6039        // Filter out packages that aren't recently used.
6040        //
6041        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6042        // should do a full dexopt.
6043        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6044            int total = pkgs.size();
6045            int skipped = 0;
6046            long now = System.currentTimeMillis();
6047            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6048                PackageParser.Package pkg = i.next();
6049                long then = pkg.mLastPackageUsageTimeInMills;
6050                if (then + mDexOptLRUThresholdInMills < now) {
6051                    if (DEBUG_DEXOPT) {
6052                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6053                              ((then == 0) ? "never" : new Date(then)));
6054                    }
6055                    i.remove();
6056                    skipped++;
6057                }
6058            }
6059            if (DEBUG_DEXOPT) {
6060                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6061            }
6062        }
6063    }
6064
6065    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6066        List<ResolveInfo> ris = null;
6067        try {
6068            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6069                    intent, null, 0, UserHandle.USER_OWNER);
6070        } catch (RemoteException e) {
6071        }
6072        ArraySet<String> pkgNames = new ArraySet<String>();
6073        if (ris != null) {
6074            for (ResolveInfo ri : ris) {
6075                pkgNames.add(ri.activityInfo.packageName);
6076            }
6077        }
6078        return pkgNames;
6079    }
6080
6081    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6082        if (DEBUG_DEXOPT) {
6083            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6084        }
6085        if (!isFirstBoot()) {
6086            try {
6087                ActivityManagerNative.getDefault().showBootMessage(
6088                        mContext.getResources().getString(R.string.android_upgrading_apk,
6089                                curr, total), true);
6090            } catch (RemoteException e) {
6091            }
6092        }
6093        PackageParser.Package p = pkg;
6094        synchronized (mInstallLock) {
6095            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6096                    false /* force dex */, false /* defer */, true /* include dependencies */);
6097        }
6098    }
6099
6100    @Override
6101    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6102        return performDexOpt(packageName, instructionSet, false);
6103    }
6104
6105    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6106        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6107        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6108        if (!dexopt && !updateUsage) {
6109            // We aren't going to dexopt or update usage, so bail early.
6110            return false;
6111        }
6112        PackageParser.Package p;
6113        final String targetInstructionSet;
6114        synchronized (mPackages) {
6115            p = mPackages.get(packageName);
6116            if (p == null) {
6117                return false;
6118            }
6119            if (updateUsage) {
6120                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6121            }
6122            mPackageUsage.write(false);
6123            if (!dexopt) {
6124                // We aren't going to dexopt, so bail early.
6125                return false;
6126            }
6127
6128            targetInstructionSet = instructionSet != null ? instructionSet :
6129                    getPrimaryInstructionSet(p.applicationInfo);
6130            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6131                return false;
6132            }
6133        }
6134
6135        synchronized (mInstallLock) {
6136            final String[] instructionSets = new String[] { targetInstructionSet };
6137            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6138                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6139            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6140        }
6141    }
6142
6143    public ArraySet<String> getPackagesThatNeedDexOpt() {
6144        ArraySet<String> pkgs = null;
6145        synchronized (mPackages) {
6146            for (PackageParser.Package p : mPackages.values()) {
6147                if (DEBUG_DEXOPT) {
6148                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6149                }
6150                if (!p.mDexOptPerformed.isEmpty()) {
6151                    continue;
6152                }
6153                if (pkgs == null) {
6154                    pkgs = new ArraySet<String>();
6155                }
6156                pkgs.add(p.packageName);
6157            }
6158        }
6159        return pkgs;
6160    }
6161
6162    public void shutdown() {
6163        mPackageUsage.write(true);
6164    }
6165
6166    @Override
6167    public void forceDexOpt(String packageName) {
6168        enforceSystemOrRoot("forceDexOpt");
6169
6170        PackageParser.Package pkg;
6171        synchronized (mPackages) {
6172            pkg = mPackages.get(packageName);
6173            if (pkg == null) {
6174                throw new IllegalArgumentException("Missing package: " + packageName);
6175            }
6176        }
6177
6178        synchronized (mInstallLock) {
6179            final String[] instructionSets = new String[] {
6180                    getPrimaryInstructionSet(pkg.applicationInfo) };
6181            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6182                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6183            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6184                throw new IllegalStateException("Failed to dexopt: " + res);
6185            }
6186        }
6187    }
6188
6189    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6190        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6191            Slog.w(TAG, "Unable to update from " + oldPkg.name
6192                    + " to " + newPkg.packageName
6193                    + ": old package not in system partition");
6194            return false;
6195        } else if (mPackages.get(oldPkg.name) != null) {
6196            Slog.w(TAG, "Unable to update from " + oldPkg.name
6197                    + " to " + newPkg.packageName
6198                    + ": old package still exists");
6199            return false;
6200        }
6201        return true;
6202    }
6203
6204    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6205        int[] users = sUserManager.getUserIds();
6206        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6207        if (res < 0) {
6208            return res;
6209        }
6210        for (int user : users) {
6211            if (user != 0) {
6212                res = mInstaller.createUserData(volumeUuid, packageName,
6213                        UserHandle.getUid(user, uid), user, seinfo);
6214                if (res < 0) {
6215                    return res;
6216                }
6217            }
6218        }
6219        return res;
6220    }
6221
6222    private int removeDataDirsLI(String volumeUuid, String packageName) {
6223        int[] users = sUserManager.getUserIds();
6224        int res = 0;
6225        for (int user : users) {
6226            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6227            if (resInner < 0) {
6228                res = resInner;
6229            }
6230        }
6231
6232        return res;
6233    }
6234
6235    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6236        int[] users = sUserManager.getUserIds();
6237        int res = 0;
6238        for (int user : users) {
6239            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6240            if (resInner < 0) {
6241                res = resInner;
6242            }
6243        }
6244        return res;
6245    }
6246
6247    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6248            PackageParser.Package changingLib) {
6249        if (file.path != null) {
6250            usesLibraryFiles.add(file.path);
6251            return;
6252        }
6253        PackageParser.Package p = mPackages.get(file.apk);
6254        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6255            // If we are doing this while in the middle of updating a library apk,
6256            // then we need to make sure to use that new apk for determining the
6257            // dependencies here.  (We haven't yet finished committing the new apk
6258            // to the package manager state.)
6259            if (p == null || p.packageName.equals(changingLib.packageName)) {
6260                p = changingLib;
6261            }
6262        }
6263        if (p != null) {
6264            usesLibraryFiles.addAll(p.getAllCodePaths());
6265        }
6266    }
6267
6268    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6269            PackageParser.Package changingLib) throws PackageManagerException {
6270        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6271            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6272            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6273            for (int i=0; i<N; i++) {
6274                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6275                if (file == null) {
6276                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6277                            "Package " + pkg.packageName + " requires unavailable shared library "
6278                            + pkg.usesLibraries.get(i) + "; failing!");
6279                }
6280                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6281            }
6282            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6283            for (int i=0; i<N; i++) {
6284                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6285                if (file == null) {
6286                    Slog.w(TAG, "Package " + pkg.packageName
6287                            + " desires unavailable shared library "
6288                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6289                } else {
6290                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6291                }
6292            }
6293            N = usesLibraryFiles.size();
6294            if (N > 0) {
6295                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6296            } else {
6297                pkg.usesLibraryFiles = null;
6298            }
6299        }
6300    }
6301
6302    private static boolean hasString(List<String> list, List<String> which) {
6303        if (list == null) {
6304            return false;
6305        }
6306        for (int i=list.size()-1; i>=0; i--) {
6307            for (int j=which.size()-1; j>=0; j--) {
6308                if (which.get(j).equals(list.get(i))) {
6309                    return true;
6310                }
6311            }
6312        }
6313        return false;
6314    }
6315
6316    private void updateAllSharedLibrariesLPw() {
6317        for (PackageParser.Package pkg : mPackages.values()) {
6318            try {
6319                updateSharedLibrariesLPw(pkg, null);
6320            } catch (PackageManagerException e) {
6321                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6322            }
6323        }
6324    }
6325
6326    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6327            PackageParser.Package changingPkg) {
6328        ArrayList<PackageParser.Package> res = null;
6329        for (PackageParser.Package pkg : mPackages.values()) {
6330            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6331                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6332                if (res == null) {
6333                    res = new ArrayList<PackageParser.Package>();
6334                }
6335                res.add(pkg);
6336                try {
6337                    updateSharedLibrariesLPw(pkg, changingPkg);
6338                } catch (PackageManagerException e) {
6339                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6340                }
6341            }
6342        }
6343        return res;
6344    }
6345
6346    /**
6347     * Derive the value of the {@code cpuAbiOverride} based on the provided
6348     * value and an optional stored value from the package settings.
6349     */
6350    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6351        String cpuAbiOverride = null;
6352
6353        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6354            cpuAbiOverride = null;
6355        } else if (abiOverride != null) {
6356            cpuAbiOverride = abiOverride;
6357        } else if (settings != null) {
6358            cpuAbiOverride = settings.cpuAbiOverrideString;
6359        }
6360
6361        return cpuAbiOverride;
6362    }
6363
6364    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6365            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6366        boolean success = false;
6367        try {
6368            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6369                    currentTime, user);
6370            success = true;
6371            return res;
6372        } finally {
6373            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6374                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6375            }
6376        }
6377    }
6378
6379    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6380            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6381        final File scanFile = new File(pkg.codePath);
6382        if (pkg.applicationInfo.getCodePath() == null ||
6383                pkg.applicationInfo.getResourcePath() == null) {
6384            // Bail out. The resource and code paths haven't been set.
6385            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6386                    "Code and resource paths haven't been set correctly");
6387        }
6388
6389        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6390            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6391        } else {
6392            // Only allow system apps to be flagged as core apps.
6393            pkg.coreApp = false;
6394        }
6395
6396        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6397            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6398        }
6399
6400        if (mCustomResolverComponentName != null &&
6401                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6402            setUpCustomResolverActivity(pkg);
6403        }
6404
6405        if (pkg.packageName.equals("android")) {
6406            synchronized (mPackages) {
6407                if (mAndroidApplication != null) {
6408                    Slog.w(TAG, "*************************************************");
6409                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6410                    Slog.w(TAG, " file=" + scanFile);
6411                    Slog.w(TAG, "*************************************************");
6412                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6413                            "Core android package being redefined.  Skipping.");
6414                }
6415
6416                // Set up information for our fall-back user intent resolution activity.
6417                mPlatformPackage = pkg;
6418                pkg.mVersionCode = mSdkVersion;
6419                mAndroidApplication = pkg.applicationInfo;
6420
6421                if (!mResolverReplaced) {
6422                    mResolveActivity.applicationInfo = mAndroidApplication;
6423                    mResolveActivity.name = ResolverActivity.class.getName();
6424                    mResolveActivity.packageName = mAndroidApplication.packageName;
6425                    mResolveActivity.processName = "system:ui";
6426                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6427                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6428                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6429                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6430                    mResolveActivity.exported = true;
6431                    mResolveActivity.enabled = true;
6432                    mResolveInfo.activityInfo = mResolveActivity;
6433                    mResolveInfo.priority = 0;
6434                    mResolveInfo.preferredOrder = 0;
6435                    mResolveInfo.match = 0;
6436                    mResolveComponentName = new ComponentName(
6437                            mAndroidApplication.packageName, mResolveActivity.name);
6438                }
6439            }
6440        }
6441
6442        if (DEBUG_PACKAGE_SCANNING) {
6443            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6444                Log.d(TAG, "Scanning package " + pkg.packageName);
6445        }
6446
6447        if (mPackages.containsKey(pkg.packageName)
6448                || mSharedLibraries.containsKey(pkg.packageName)) {
6449            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6450                    "Application package " + pkg.packageName
6451                    + " already installed.  Skipping duplicate.");
6452        }
6453
6454        // If we're only installing presumed-existing packages, require that the
6455        // scanned APK is both already known and at the path previously established
6456        // for it.  Previously unknown packages we pick up normally, but if we have an
6457        // a priori expectation about this package's install presence, enforce it.
6458        // With a singular exception for new system packages. When an OTA contains
6459        // a new system package, we allow the codepath to change from a system location
6460        // to the user-installed location. If we don't allow this change, any newer,
6461        // user-installed version of the application will be ignored.
6462        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6463            if (mExpectingBetter.containsKey(pkg.packageName)) {
6464                logCriticalInfo(Log.WARN,
6465                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6466            } else {
6467                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6468                if (known != null) {
6469                    if (DEBUG_PACKAGE_SCANNING) {
6470                        Log.d(TAG, "Examining " + pkg.codePath
6471                                + " and requiring known paths " + known.codePathString
6472                                + " & " + known.resourcePathString);
6473                    }
6474                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6475                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6476                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6477                                "Application package " + pkg.packageName
6478                                + " found at " + pkg.applicationInfo.getCodePath()
6479                                + " but expected at " + known.codePathString + "; ignoring.");
6480                    }
6481                }
6482            }
6483        }
6484
6485        // Initialize package source and resource directories
6486        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6487        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6488
6489        SharedUserSetting suid = null;
6490        PackageSetting pkgSetting = null;
6491
6492        if (!isSystemApp(pkg)) {
6493            // Only system apps can use these features.
6494            pkg.mOriginalPackages = null;
6495            pkg.mRealPackage = null;
6496            pkg.mAdoptPermissions = null;
6497        }
6498
6499        // writer
6500        synchronized (mPackages) {
6501            if (pkg.mSharedUserId != null) {
6502                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6503                if (suid == null) {
6504                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6505                            "Creating application package " + pkg.packageName
6506                            + " for shared user failed");
6507                }
6508                if (DEBUG_PACKAGE_SCANNING) {
6509                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6510                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6511                                + "): packages=" + suid.packages);
6512                }
6513            }
6514
6515            // Check if we are renaming from an original package name.
6516            PackageSetting origPackage = null;
6517            String realName = null;
6518            if (pkg.mOriginalPackages != null) {
6519                // This package may need to be renamed to a previously
6520                // installed name.  Let's check on that...
6521                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6522                if (pkg.mOriginalPackages.contains(renamed)) {
6523                    // This package had originally been installed as the
6524                    // original name, and we have already taken care of
6525                    // transitioning to the new one.  Just update the new
6526                    // one to continue using the old name.
6527                    realName = pkg.mRealPackage;
6528                    if (!pkg.packageName.equals(renamed)) {
6529                        // Callers into this function may have already taken
6530                        // care of renaming the package; only do it here if
6531                        // it is not already done.
6532                        pkg.setPackageName(renamed);
6533                    }
6534
6535                } else {
6536                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6537                        if ((origPackage = mSettings.peekPackageLPr(
6538                                pkg.mOriginalPackages.get(i))) != null) {
6539                            // We do have the package already installed under its
6540                            // original name...  should we use it?
6541                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6542                                // New package is not compatible with original.
6543                                origPackage = null;
6544                                continue;
6545                            } else if (origPackage.sharedUser != null) {
6546                                // Make sure uid is compatible between packages.
6547                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6548                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6549                                            + " to " + pkg.packageName + ": old uid "
6550                                            + origPackage.sharedUser.name
6551                                            + " differs from " + pkg.mSharedUserId);
6552                                    origPackage = null;
6553                                    continue;
6554                                }
6555                            } else {
6556                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6557                                        + pkg.packageName + " to old name " + origPackage.name);
6558                            }
6559                            break;
6560                        }
6561                    }
6562                }
6563            }
6564
6565            if (mTransferedPackages.contains(pkg.packageName)) {
6566                Slog.w(TAG, "Package " + pkg.packageName
6567                        + " was transferred to another, but its .apk remains");
6568            }
6569
6570            // Just create the setting, don't add it yet. For already existing packages
6571            // the PkgSetting exists already and doesn't have to be created.
6572            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6573                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6574                    pkg.applicationInfo.primaryCpuAbi,
6575                    pkg.applicationInfo.secondaryCpuAbi,
6576                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6577                    user, false);
6578            if (pkgSetting == null) {
6579                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6580                        "Creating application package " + pkg.packageName + " failed");
6581            }
6582
6583            if (pkgSetting.origPackage != null) {
6584                // If we are first transitioning from an original package,
6585                // fix up the new package's name now.  We need to do this after
6586                // looking up the package under its new name, so getPackageLP
6587                // can take care of fiddling things correctly.
6588                pkg.setPackageName(origPackage.name);
6589
6590                // File a report about this.
6591                String msg = "New package " + pkgSetting.realName
6592                        + " renamed to replace old package " + pkgSetting.name;
6593                reportSettingsProblem(Log.WARN, msg);
6594
6595                // Make a note of it.
6596                mTransferedPackages.add(origPackage.name);
6597
6598                // No longer need to retain this.
6599                pkgSetting.origPackage = null;
6600            }
6601
6602            if (realName != null) {
6603                // Make a note of it.
6604                mTransferedPackages.add(pkg.packageName);
6605            }
6606
6607            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6608                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6609            }
6610
6611            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6612                // Check all shared libraries and map to their actual file path.
6613                // We only do this here for apps not on a system dir, because those
6614                // are the only ones that can fail an install due to this.  We
6615                // will take care of the system apps by updating all of their
6616                // library paths after the scan is done.
6617                updateSharedLibrariesLPw(pkg, null);
6618            }
6619
6620            if (mFoundPolicyFile) {
6621                SELinuxMMAC.assignSeinfoValue(pkg);
6622            }
6623
6624            pkg.applicationInfo.uid = pkgSetting.appId;
6625            pkg.mExtras = pkgSetting;
6626            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6627                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6628                    // We just determined the app is signed correctly, so bring
6629                    // over the latest parsed certs.
6630                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6631                } else {
6632                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6633                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6634                                "Package " + pkg.packageName + " upgrade keys do not match the "
6635                                + "previously installed version");
6636                    } else {
6637                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6638                        String msg = "System package " + pkg.packageName
6639                            + " signature changed; retaining data.";
6640                        reportSettingsProblem(Log.WARN, msg);
6641                    }
6642                }
6643            } else {
6644                try {
6645                    verifySignaturesLP(pkgSetting, pkg);
6646                    // We just determined the app is signed correctly, so bring
6647                    // over the latest parsed certs.
6648                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6649                } catch (PackageManagerException e) {
6650                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6651                        throw e;
6652                    }
6653                    // The signature has changed, but this package is in the system
6654                    // image...  let's recover!
6655                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6656                    // However...  if this package is part of a shared user, but it
6657                    // doesn't match the signature of the shared user, let's fail.
6658                    // What this means is that you can't change the signatures
6659                    // associated with an overall shared user, which doesn't seem all
6660                    // that unreasonable.
6661                    if (pkgSetting.sharedUser != null) {
6662                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6663                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6664                            throw new PackageManagerException(
6665                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6666                                            "Signature mismatch for shared user : "
6667                                            + pkgSetting.sharedUser);
6668                        }
6669                    }
6670                    // File a report about this.
6671                    String msg = "System package " + pkg.packageName
6672                        + " signature changed; retaining data.";
6673                    reportSettingsProblem(Log.WARN, msg);
6674                }
6675            }
6676            // Verify that this new package doesn't have any content providers
6677            // that conflict with existing packages.  Only do this if the
6678            // package isn't already installed, since we don't want to break
6679            // things that are installed.
6680            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6681                final int N = pkg.providers.size();
6682                int i;
6683                for (i=0; i<N; i++) {
6684                    PackageParser.Provider p = pkg.providers.get(i);
6685                    if (p.info.authority != null) {
6686                        String names[] = p.info.authority.split(";");
6687                        for (int j = 0; j < names.length; j++) {
6688                            if (mProvidersByAuthority.containsKey(names[j])) {
6689                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6690                                final String otherPackageName =
6691                                        ((other != null && other.getComponentName() != null) ?
6692                                                other.getComponentName().getPackageName() : "?");
6693                                throw new PackageManagerException(
6694                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6695                                                "Can't install because provider name " + names[j]
6696                                                + " (in package " + pkg.applicationInfo.packageName
6697                                                + ") is already used by " + otherPackageName);
6698                            }
6699                        }
6700                    }
6701                }
6702            }
6703
6704            if (pkg.mAdoptPermissions != null) {
6705                // This package wants to adopt ownership of permissions from
6706                // another package.
6707                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6708                    final String origName = pkg.mAdoptPermissions.get(i);
6709                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6710                    if (orig != null) {
6711                        if (verifyPackageUpdateLPr(orig, pkg)) {
6712                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6713                                    + pkg.packageName);
6714                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6715                        }
6716                    }
6717                }
6718            }
6719        }
6720
6721        final String pkgName = pkg.packageName;
6722
6723        final long scanFileTime = scanFile.lastModified();
6724        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6725        pkg.applicationInfo.processName = fixProcessName(
6726                pkg.applicationInfo.packageName,
6727                pkg.applicationInfo.processName,
6728                pkg.applicationInfo.uid);
6729
6730        File dataPath;
6731        if (mPlatformPackage == pkg) {
6732            // The system package is special.
6733            dataPath = new File(Environment.getDataDirectory(), "system");
6734
6735            pkg.applicationInfo.dataDir = dataPath.getPath();
6736
6737        } else {
6738            // This is a normal package, need to make its data directory.
6739            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6740                    UserHandle.USER_OWNER, pkg.packageName);
6741
6742            boolean uidError = false;
6743            if (dataPath.exists()) {
6744                int currentUid = 0;
6745                try {
6746                    StructStat stat = Os.stat(dataPath.getPath());
6747                    currentUid = stat.st_uid;
6748                } catch (ErrnoException e) {
6749                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6750                }
6751
6752                // If we have mismatched owners for the data path, we have a problem.
6753                if (currentUid != pkg.applicationInfo.uid) {
6754                    boolean recovered = false;
6755                    if (currentUid == 0) {
6756                        // The directory somehow became owned by root.  Wow.
6757                        // This is probably because the system was stopped while
6758                        // installd was in the middle of messing with its libs
6759                        // directory.  Ask installd to fix that.
6760                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6761                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6762                        if (ret >= 0) {
6763                            recovered = true;
6764                            String msg = "Package " + pkg.packageName
6765                                    + " unexpectedly changed to uid 0; recovered to " +
6766                                    + pkg.applicationInfo.uid;
6767                            reportSettingsProblem(Log.WARN, msg);
6768                        }
6769                    }
6770                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6771                            || (scanFlags&SCAN_BOOTING) != 0)) {
6772                        // If this is a system app, we can at least delete its
6773                        // current data so the application will still work.
6774                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6775                        if (ret >= 0) {
6776                            // TODO: Kill the processes first
6777                            // Old data gone!
6778                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6779                                    ? "System package " : "Third party package ";
6780                            String msg = prefix + pkg.packageName
6781                                    + " has changed from uid: "
6782                                    + currentUid + " to "
6783                                    + pkg.applicationInfo.uid + "; old data erased";
6784                            reportSettingsProblem(Log.WARN, msg);
6785                            recovered = true;
6786
6787                            // And now re-install the app.
6788                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6789                                    pkg.applicationInfo.seinfo);
6790                            if (ret == -1) {
6791                                // Ack should not happen!
6792                                msg = prefix + pkg.packageName
6793                                        + " could not have data directory re-created after delete.";
6794                                reportSettingsProblem(Log.WARN, msg);
6795                                throw new PackageManagerException(
6796                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6797                            }
6798                        }
6799                        if (!recovered) {
6800                            mHasSystemUidErrors = true;
6801                        }
6802                    } else if (!recovered) {
6803                        // If we allow this install to proceed, we will be broken.
6804                        // Abort, abort!
6805                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6806                                "scanPackageLI");
6807                    }
6808                    if (!recovered) {
6809                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6810                            + pkg.applicationInfo.uid + "/fs_"
6811                            + currentUid;
6812                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6813                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6814                        String msg = "Package " + pkg.packageName
6815                                + " has mismatched uid: "
6816                                + currentUid + " on disk, "
6817                                + pkg.applicationInfo.uid + " in settings";
6818                        // writer
6819                        synchronized (mPackages) {
6820                            mSettings.mReadMessages.append(msg);
6821                            mSettings.mReadMessages.append('\n');
6822                            uidError = true;
6823                            if (!pkgSetting.uidError) {
6824                                reportSettingsProblem(Log.ERROR, msg);
6825                            }
6826                        }
6827                    }
6828                }
6829                pkg.applicationInfo.dataDir = dataPath.getPath();
6830                if (mShouldRestoreconData) {
6831                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6832                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6833                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6834                }
6835            } else {
6836                if (DEBUG_PACKAGE_SCANNING) {
6837                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6838                        Log.v(TAG, "Want this data dir: " + dataPath);
6839                }
6840                //invoke installer to do the actual installation
6841                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6842                        pkg.applicationInfo.seinfo);
6843                if (ret < 0) {
6844                    // Error from installer
6845                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6846                            "Unable to create data dirs [errorCode=" + ret + "]");
6847                }
6848
6849                if (dataPath.exists()) {
6850                    pkg.applicationInfo.dataDir = dataPath.getPath();
6851                } else {
6852                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6853                    pkg.applicationInfo.dataDir = null;
6854                }
6855            }
6856
6857            pkgSetting.uidError = uidError;
6858        }
6859
6860        final String path = scanFile.getPath();
6861        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6862
6863        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6864            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6865
6866            // Some system apps still use directory structure for native libraries
6867            // in which case we might end up not detecting abi solely based on apk
6868            // structure. Try to detect abi based on directory structure.
6869            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6870                    pkg.applicationInfo.primaryCpuAbi == null) {
6871                setBundledAppAbisAndRoots(pkg, pkgSetting);
6872                setNativeLibraryPaths(pkg);
6873            }
6874
6875        } else {
6876            if ((scanFlags & SCAN_MOVE) != 0) {
6877                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6878                // but we already have this packages package info in the PackageSetting. We just
6879                // use that and derive the native library path based on the new codepath.
6880                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6881                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6882            }
6883
6884            // Set native library paths again. For moves, the path will be updated based on the
6885            // ABIs we've determined above. For non-moves, the path will be updated based on the
6886            // ABIs we determined during compilation, but the path will depend on the final
6887            // package path (after the rename away from the stage path).
6888            setNativeLibraryPaths(pkg);
6889        }
6890
6891        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6892        final int[] userIds = sUserManager.getUserIds();
6893        synchronized (mInstallLock) {
6894            // Make sure all user data directories are ready to roll; we're okay
6895            // if they already exist
6896            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6897                for (int userId : userIds) {
6898                    if (userId != 0) {
6899                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6900                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6901                                pkg.applicationInfo.seinfo);
6902                    }
6903                }
6904            }
6905
6906            // Create a native library symlink only if we have native libraries
6907            // and if the native libraries are 32 bit libraries. We do not provide
6908            // this symlink for 64 bit libraries.
6909            if (pkg.applicationInfo.primaryCpuAbi != null &&
6910                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6911                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6912                for (int userId : userIds) {
6913                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6914                            nativeLibPath, userId) < 0) {
6915                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6916                                "Failed linking native library dir (user=" + userId + ")");
6917                    }
6918                }
6919            }
6920        }
6921
6922        // This is a special case for the "system" package, where the ABI is
6923        // dictated by the zygote configuration (and init.rc). We should keep track
6924        // of this ABI so that we can deal with "normal" applications that run under
6925        // the same UID correctly.
6926        if (mPlatformPackage == pkg) {
6927            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6928                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6929        }
6930
6931        // If there's a mismatch between the abi-override in the package setting
6932        // and the abiOverride specified for the install. Warn about this because we
6933        // would've already compiled the app without taking the package setting into
6934        // account.
6935        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6936            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6937                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6938                        " for package: " + pkg.packageName);
6939            }
6940        }
6941
6942        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6943        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6944        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6945
6946        // Copy the derived override back to the parsed package, so that we can
6947        // update the package settings accordingly.
6948        pkg.cpuAbiOverride = cpuAbiOverride;
6949
6950        if (DEBUG_ABI_SELECTION) {
6951            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6952                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6953                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6954        }
6955
6956        // Push the derived path down into PackageSettings so we know what to
6957        // clean up at uninstall time.
6958        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6959
6960        if (DEBUG_ABI_SELECTION) {
6961            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6962                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6963                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6964        }
6965
6966        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6967            // We don't do this here during boot because we can do it all
6968            // at once after scanning all existing packages.
6969            //
6970            // We also do this *before* we perform dexopt on this package, so that
6971            // we can avoid redundant dexopts, and also to make sure we've got the
6972            // code and package path correct.
6973            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6974                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6975        }
6976
6977        if ((scanFlags & SCAN_NO_DEX) == 0) {
6978            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6979                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6980            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6981                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6982            }
6983        }
6984        if (mFactoryTest && pkg.requestedPermissions.contains(
6985                android.Manifest.permission.FACTORY_TEST)) {
6986            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6987        }
6988
6989        ArrayList<PackageParser.Package> clientLibPkgs = null;
6990
6991        // writer
6992        synchronized (mPackages) {
6993            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6994                // Only system apps can add new shared libraries.
6995                if (pkg.libraryNames != null) {
6996                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6997                        String name = pkg.libraryNames.get(i);
6998                        boolean allowed = false;
6999                        if (pkg.isUpdatedSystemApp()) {
7000                            // New library entries can only be added through the
7001                            // system image.  This is important to get rid of a lot
7002                            // of nasty edge cases: for example if we allowed a non-
7003                            // system update of the app to add a library, then uninstalling
7004                            // the update would make the library go away, and assumptions
7005                            // we made such as through app install filtering would now
7006                            // have allowed apps on the device which aren't compatible
7007                            // with it.  Better to just have the restriction here, be
7008                            // conservative, and create many fewer cases that can negatively
7009                            // impact the user experience.
7010                            final PackageSetting sysPs = mSettings
7011                                    .getDisabledSystemPkgLPr(pkg.packageName);
7012                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7013                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7014                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7015                                        allowed = true;
7016                                        allowed = true;
7017                                        break;
7018                                    }
7019                                }
7020                            }
7021                        } else {
7022                            allowed = true;
7023                        }
7024                        if (allowed) {
7025                            if (!mSharedLibraries.containsKey(name)) {
7026                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7027                            } else if (!name.equals(pkg.packageName)) {
7028                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7029                                        + name + " already exists; skipping");
7030                            }
7031                        } else {
7032                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7033                                    + name + " that is not declared on system image; skipping");
7034                        }
7035                    }
7036                    if ((scanFlags&SCAN_BOOTING) == 0) {
7037                        // If we are not booting, we need to update any applications
7038                        // that are clients of our shared library.  If we are booting,
7039                        // this will all be done once the scan is complete.
7040                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7041                    }
7042                }
7043            }
7044        }
7045
7046        // We also need to dexopt any apps that are dependent on this library.  Note that
7047        // if these fail, we should abort the install since installing the library will
7048        // result in some apps being broken.
7049        if (clientLibPkgs != null) {
7050            if ((scanFlags & SCAN_NO_DEX) == 0) {
7051                for (int i = 0; i < clientLibPkgs.size(); i++) {
7052                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7053                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7054                            null /* instruction sets */, forceDex,
7055                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7056                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7057                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7058                                "scanPackageLI failed to dexopt clientLibPkgs");
7059                    }
7060                }
7061            }
7062        }
7063
7064        // Also need to kill any apps that are dependent on the library.
7065        if (clientLibPkgs != null) {
7066            for (int i=0; i<clientLibPkgs.size(); i++) {
7067                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7068                killApplication(clientPkg.applicationInfo.packageName,
7069                        clientPkg.applicationInfo.uid, "update lib");
7070            }
7071        }
7072
7073        // Make sure we're not adding any bogus keyset info
7074        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7075        ksms.assertScannedPackageValid(pkg);
7076
7077        // writer
7078        synchronized (mPackages) {
7079            // We don't expect installation to fail beyond this point
7080
7081            // Add the new setting to mSettings
7082            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7083            // Add the new setting to mPackages
7084            mPackages.put(pkg.applicationInfo.packageName, pkg);
7085            // Make sure we don't accidentally delete its data.
7086            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7087            while (iter.hasNext()) {
7088                PackageCleanItem item = iter.next();
7089                if (pkgName.equals(item.packageName)) {
7090                    iter.remove();
7091                }
7092            }
7093
7094            // Take care of first install / last update times.
7095            if (currentTime != 0) {
7096                if (pkgSetting.firstInstallTime == 0) {
7097                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7098                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7099                    pkgSetting.lastUpdateTime = currentTime;
7100                }
7101            } else if (pkgSetting.firstInstallTime == 0) {
7102                // We need *something*.  Take time time stamp of the file.
7103                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7104            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7105                if (scanFileTime != pkgSetting.timeStamp) {
7106                    // A package on the system image has changed; consider this
7107                    // to be an update.
7108                    pkgSetting.lastUpdateTime = scanFileTime;
7109                }
7110            }
7111
7112            // Add the package's KeySets to the global KeySetManagerService
7113            ksms.addScannedPackageLPw(pkg);
7114
7115            int N = pkg.providers.size();
7116            StringBuilder r = null;
7117            int i;
7118            for (i=0; i<N; i++) {
7119                PackageParser.Provider p = pkg.providers.get(i);
7120                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7121                        p.info.processName, pkg.applicationInfo.uid);
7122                mProviders.addProvider(p);
7123                p.syncable = p.info.isSyncable;
7124                if (p.info.authority != null) {
7125                    String names[] = p.info.authority.split(";");
7126                    p.info.authority = null;
7127                    for (int j = 0; j < names.length; j++) {
7128                        if (j == 1 && p.syncable) {
7129                            // We only want the first authority for a provider to possibly be
7130                            // syncable, so if we already added this provider using a different
7131                            // authority clear the syncable flag. We copy the provider before
7132                            // changing it because the mProviders object contains a reference
7133                            // to a provider that we don't want to change.
7134                            // Only do this for the second authority since the resulting provider
7135                            // object can be the same for all future authorities for this provider.
7136                            p = new PackageParser.Provider(p);
7137                            p.syncable = false;
7138                        }
7139                        if (!mProvidersByAuthority.containsKey(names[j])) {
7140                            mProvidersByAuthority.put(names[j], p);
7141                            if (p.info.authority == null) {
7142                                p.info.authority = names[j];
7143                            } else {
7144                                p.info.authority = p.info.authority + ";" + names[j];
7145                            }
7146                            if (DEBUG_PACKAGE_SCANNING) {
7147                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7148                                    Log.d(TAG, "Registered content provider: " + names[j]
7149                                            + ", className = " + p.info.name + ", isSyncable = "
7150                                            + p.info.isSyncable);
7151                            }
7152                        } else {
7153                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7154                            Slog.w(TAG, "Skipping provider name " + names[j] +
7155                                    " (in package " + pkg.applicationInfo.packageName +
7156                                    "): name already used by "
7157                                    + ((other != null && other.getComponentName() != null)
7158                                            ? other.getComponentName().getPackageName() : "?"));
7159                        }
7160                    }
7161                }
7162                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7163                    if (r == null) {
7164                        r = new StringBuilder(256);
7165                    } else {
7166                        r.append(' ');
7167                    }
7168                    r.append(p.info.name);
7169                }
7170            }
7171            if (r != null) {
7172                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7173            }
7174
7175            N = pkg.services.size();
7176            r = null;
7177            for (i=0; i<N; i++) {
7178                PackageParser.Service s = pkg.services.get(i);
7179                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7180                        s.info.processName, pkg.applicationInfo.uid);
7181                mServices.addService(s);
7182                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7183                    if (r == null) {
7184                        r = new StringBuilder(256);
7185                    } else {
7186                        r.append(' ');
7187                    }
7188                    r.append(s.info.name);
7189                }
7190            }
7191            if (r != null) {
7192                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7193            }
7194
7195            N = pkg.receivers.size();
7196            r = null;
7197            for (i=0; i<N; i++) {
7198                PackageParser.Activity a = pkg.receivers.get(i);
7199                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7200                        a.info.processName, pkg.applicationInfo.uid);
7201                mReceivers.addActivity(a, "receiver");
7202                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7203                    if (r == null) {
7204                        r = new StringBuilder(256);
7205                    } else {
7206                        r.append(' ');
7207                    }
7208                    r.append(a.info.name);
7209                }
7210            }
7211            if (r != null) {
7212                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7213            }
7214
7215            N = pkg.activities.size();
7216            r = null;
7217            for (i=0; i<N; i++) {
7218                PackageParser.Activity a = pkg.activities.get(i);
7219                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7220                        a.info.processName, pkg.applicationInfo.uid);
7221                mActivities.addActivity(a, "activity");
7222                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7223                    if (r == null) {
7224                        r = new StringBuilder(256);
7225                    } else {
7226                        r.append(' ');
7227                    }
7228                    r.append(a.info.name);
7229                }
7230            }
7231            if (r != null) {
7232                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7233            }
7234
7235            N = pkg.permissionGroups.size();
7236            r = null;
7237            for (i=0; i<N; i++) {
7238                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7239                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7240                if (cur == null) {
7241                    mPermissionGroups.put(pg.info.name, pg);
7242                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7243                        if (r == null) {
7244                            r = new StringBuilder(256);
7245                        } else {
7246                            r.append(' ');
7247                        }
7248                        r.append(pg.info.name);
7249                    }
7250                } else {
7251                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7252                            + pg.info.packageName + " ignored: original from "
7253                            + cur.info.packageName);
7254                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7255                        if (r == null) {
7256                            r = new StringBuilder(256);
7257                        } else {
7258                            r.append(' ');
7259                        }
7260                        r.append("DUP:");
7261                        r.append(pg.info.name);
7262                    }
7263                }
7264            }
7265            if (r != null) {
7266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7267            }
7268
7269            N = pkg.permissions.size();
7270            r = null;
7271            for (i=0; i<N; i++) {
7272                PackageParser.Permission p = pkg.permissions.get(i);
7273
7274                // Now that permission groups have a special meaning, we ignore permission
7275                // groups for legacy apps to prevent unexpected behavior. In particular,
7276                // permissions for one app being granted to someone just becuase they happen
7277                // to be in a group defined by another app (before this had no implications).
7278                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7279                    p.group = mPermissionGroups.get(p.info.group);
7280                    // Warn for a permission in an unknown group.
7281                    if (p.info.group != null && p.group == null) {
7282                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7283                                + p.info.packageName + " in an unknown group " + p.info.group);
7284                    }
7285                }
7286
7287                ArrayMap<String, BasePermission> permissionMap =
7288                        p.tree ? mSettings.mPermissionTrees
7289                                : mSettings.mPermissions;
7290                BasePermission bp = permissionMap.get(p.info.name);
7291
7292                // Allow system apps to redefine non-system permissions
7293                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7294                    final boolean currentOwnerIsSystem = (bp.perm != null
7295                            && isSystemApp(bp.perm.owner));
7296                    if (isSystemApp(p.owner)) {
7297                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7298                            // It's a built-in permission and no owner, take ownership now
7299                            bp.packageSetting = pkgSetting;
7300                            bp.perm = p;
7301                            bp.uid = pkg.applicationInfo.uid;
7302                            bp.sourcePackage = p.info.packageName;
7303                        } else if (!currentOwnerIsSystem) {
7304                            String msg = "New decl " + p.owner + " of permission  "
7305                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7306                            reportSettingsProblem(Log.WARN, msg);
7307                            bp = null;
7308                        }
7309                    }
7310                }
7311
7312                if (bp == null) {
7313                    bp = new BasePermission(p.info.name, p.info.packageName,
7314                            BasePermission.TYPE_NORMAL);
7315                    permissionMap.put(p.info.name, bp);
7316                }
7317
7318                if (bp.perm == null) {
7319                    if (bp.sourcePackage == null
7320                            || bp.sourcePackage.equals(p.info.packageName)) {
7321                        BasePermission tree = findPermissionTreeLP(p.info.name);
7322                        if (tree == null
7323                                || tree.sourcePackage.equals(p.info.packageName)) {
7324                            bp.packageSetting = pkgSetting;
7325                            bp.perm = p;
7326                            bp.uid = pkg.applicationInfo.uid;
7327                            bp.sourcePackage = p.info.packageName;
7328                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7329                                if (r == null) {
7330                                    r = new StringBuilder(256);
7331                                } else {
7332                                    r.append(' ');
7333                                }
7334                                r.append(p.info.name);
7335                            }
7336                        } else {
7337                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7338                                    + p.info.packageName + " ignored: base tree "
7339                                    + tree.name + " is from package "
7340                                    + tree.sourcePackage);
7341                        }
7342                    } else {
7343                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7344                                + p.info.packageName + " ignored: original from "
7345                                + bp.sourcePackage);
7346                    }
7347                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7348                    if (r == null) {
7349                        r = new StringBuilder(256);
7350                    } else {
7351                        r.append(' ');
7352                    }
7353                    r.append("DUP:");
7354                    r.append(p.info.name);
7355                }
7356                if (bp.perm == p) {
7357                    bp.protectionLevel = p.info.protectionLevel;
7358                }
7359            }
7360
7361            if (r != null) {
7362                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7363            }
7364
7365            N = pkg.instrumentation.size();
7366            r = null;
7367            for (i=0; i<N; i++) {
7368                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7369                a.info.packageName = pkg.applicationInfo.packageName;
7370                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7371                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7372                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7373                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7374                a.info.dataDir = pkg.applicationInfo.dataDir;
7375
7376                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7377                // need other information about the application, like the ABI and what not ?
7378                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7379                mInstrumentation.put(a.getComponentName(), a);
7380                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7381                    if (r == null) {
7382                        r = new StringBuilder(256);
7383                    } else {
7384                        r.append(' ');
7385                    }
7386                    r.append(a.info.name);
7387                }
7388            }
7389            if (r != null) {
7390                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7391            }
7392
7393            if (pkg.protectedBroadcasts != null) {
7394                N = pkg.protectedBroadcasts.size();
7395                for (i=0; i<N; i++) {
7396                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7397                }
7398            }
7399
7400            pkgSetting.setTimeStamp(scanFileTime);
7401
7402            // Create idmap files for pairs of (packages, overlay packages).
7403            // Note: "android", ie framework-res.apk, is handled by native layers.
7404            if (pkg.mOverlayTarget != null) {
7405                // This is an overlay package.
7406                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7407                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7408                        mOverlays.put(pkg.mOverlayTarget,
7409                                new ArrayMap<String, PackageParser.Package>());
7410                    }
7411                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7412                    map.put(pkg.packageName, pkg);
7413                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7414                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7415                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7416                                "scanPackageLI failed to createIdmap");
7417                    }
7418                }
7419            } else if (mOverlays.containsKey(pkg.packageName) &&
7420                    !pkg.packageName.equals("android")) {
7421                // This is a regular package, with one or more known overlay packages.
7422                createIdmapsForPackageLI(pkg);
7423            }
7424        }
7425
7426        return pkg;
7427    }
7428
7429    /**
7430     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7431     * is derived purely on the basis of the contents of {@code scanFile} and
7432     * {@code cpuAbiOverride}.
7433     *
7434     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7435     */
7436    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7437                                 String cpuAbiOverride, boolean extractLibs)
7438            throws PackageManagerException {
7439        // TODO: We can probably be smarter about this stuff. For installed apps,
7440        // we can calculate this information at install time once and for all. For
7441        // system apps, we can probably assume that this information doesn't change
7442        // after the first boot scan. As things stand, we do lots of unnecessary work.
7443
7444        // Give ourselves some initial paths; we'll come back for another
7445        // pass once we've determined ABI below.
7446        setNativeLibraryPaths(pkg);
7447
7448        // We would never need to extract libs for forward-locked and external packages,
7449        // since the container service will do it for us. We shouldn't attempt to
7450        // extract libs from system app when it was not updated.
7451        if (pkg.isForwardLocked() || isExternal(pkg) ||
7452            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7453            extractLibs = false;
7454        }
7455
7456        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7457        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7458
7459        NativeLibraryHelper.Handle handle = null;
7460        try {
7461            handle = NativeLibraryHelper.Handle.create(scanFile);
7462            // TODO(multiArch): This can be null for apps that didn't go through the
7463            // usual installation process. We can calculate it again, like we
7464            // do during install time.
7465            //
7466            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7467            // unnecessary.
7468            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7469
7470            // Null out the abis so that they can be recalculated.
7471            pkg.applicationInfo.primaryCpuAbi = null;
7472            pkg.applicationInfo.secondaryCpuAbi = null;
7473            if (isMultiArch(pkg.applicationInfo)) {
7474                // Warn if we've set an abiOverride for multi-lib packages..
7475                // By definition, we need to copy both 32 and 64 bit libraries for
7476                // such packages.
7477                if (pkg.cpuAbiOverride != null
7478                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7479                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7480                }
7481
7482                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7483                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7484                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7485                    if (extractLibs) {
7486                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7487                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7488                                useIsaSpecificSubdirs);
7489                    } else {
7490                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7491                    }
7492                }
7493
7494                maybeThrowExceptionForMultiArchCopy(
7495                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7496
7497                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7498                    if (extractLibs) {
7499                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7500                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7501                                useIsaSpecificSubdirs);
7502                    } else {
7503                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7504                    }
7505                }
7506
7507                maybeThrowExceptionForMultiArchCopy(
7508                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7509
7510                if (abi64 >= 0) {
7511                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7512                }
7513
7514                if (abi32 >= 0) {
7515                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7516                    if (abi64 >= 0) {
7517                        pkg.applicationInfo.secondaryCpuAbi = abi;
7518                    } else {
7519                        pkg.applicationInfo.primaryCpuAbi = abi;
7520                    }
7521                }
7522            } else {
7523                String[] abiList = (cpuAbiOverride != null) ?
7524                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7525
7526                // Enable gross and lame hacks for apps that are built with old
7527                // SDK tools. We must scan their APKs for renderscript bitcode and
7528                // not launch them if it's present. Don't bother checking on devices
7529                // that don't have 64 bit support.
7530                boolean needsRenderScriptOverride = false;
7531                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7532                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7533                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7534                    needsRenderScriptOverride = true;
7535                }
7536
7537                final int copyRet;
7538                if (extractLibs) {
7539                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7540                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7541                } else {
7542                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7543                }
7544
7545                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7546                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7547                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7548                }
7549
7550                if (copyRet >= 0) {
7551                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7552                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7553                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7554                } else if (needsRenderScriptOverride) {
7555                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7556                }
7557            }
7558        } catch (IOException ioe) {
7559            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7560        } finally {
7561            IoUtils.closeQuietly(handle);
7562        }
7563
7564        // Now that we've calculated the ABIs and determined if it's an internal app,
7565        // we will go ahead and populate the nativeLibraryPath.
7566        setNativeLibraryPaths(pkg);
7567    }
7568
7569    /**
7570     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7571     * i.e, so that all packages can be run inside a single process if required.
7572     *
7573     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7574     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7575     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7576     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7577     * updating a package that belongs to a shared user.
7578     *
7579     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7580     * adds unnecessary complexity.
7581     */
7582    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7583            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7584        String requiredInstructionSet = null;
7585        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7586            requiredInstructionSet = VMRuntime.getInstructionSet(
7587                     scannedPackage.applicationInfo.primaryCpuAbi);
7588        }
7589
7590        PackageSetting requirer = null;
7591        for (PackageSetting ps : packagesForUser) {
7592            // If packagesForUser contains scannedPackage, we skip it. This will happen
7593            // when scannedPackage is an update of an existing package. Without this check,
7594            // we will never be able to change the ABI of any package belonging to a shared
7595            // user, even if it's compatible with other packages.
7596            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7597                if (ps.primaryCpuAbiString == null) {
7598                    continue;
7599                }
7600
7601                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7602                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7603                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7604                    // this but there's not much we can do.
7605                    String errorMessage = "Instruction set mismatch, "
7606                            + ((requirer == null) ? "[caller]" : requirer)
7607                            + " requires " + requiredInstructionSet + " whereas " + ps
7608                            + " requires " + instructionSet;
7609                    Slog.w(TAG, errorMessage);
7610                }
7611
7612                if (requiredInstructionSet == null) {
7613                    requiredInstructionSet = instructionSet;
7614                    requirer = ps;
7615                }
7616            }
7617        }
7618
7619        if (requiredInstructionSet != null) {
7620            String adjustedAbi;
7621            if (requirer != null) {
7622                // requirer != null implies that either scannedPackage was null or that scannedPackage
7623                // did not require an ABI, in which case we have to adjust scannedPackage to match
7624                // the ABI of the set (which is the same as requirer's ABI)
7625                adjustedAbi = requirer.primaryCpuAbiString;
7626                if (scannedPackage != null) {
7627                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7628                }
7629            } else {
7630                // requirer == null implies that we're updating all ABIs in the set to
7631                // match scannedPackage.
7632                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7633            }
7634
7635            for (PackageSetting ps : packagesForUser) {
7636                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7637                    if (ps.primaryCpuAbiString != null) {
7638                        continue;
7639                    }
7640
7641                    ps.primaryCpuAbiString = adjustedAbi;
7642                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7643                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7644                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7645
7646                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7647                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7648                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7649                            ps.primaryCpuAbiString = null;
7650                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7651                            return;
7652                        } else {
7653                            mInstaller.rmdex(ps.codePathString,
7654                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7655                        }
7656                    }
7657                }
7658            }
7659        }
7660    }
7661
7662    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7663        synchronized (mPackages) {
7664            mResolverReplaced = true;
7665            // Set up information for custom user intent resolution activity.
7666            mResolveActivity.applicationInfo = pkg.applicationInfo;
7667            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7668            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7669            mResolveActivity.processName = pkg.applicationInfo.packageName;
7670            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7671            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7672                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7673            mResolveActivity.theme = 0;
7674            mResolveActivity.exported = true;
7675            mResolveActivity.enabled = true;
7676            mResolveInfo.activityInfo = mResolveActivity;
7677            mResolveInfo.priority = 0;
7678            mResolveInfo.preferredOrder = 0;
7679            mResolveInfo.match = 0;
7680            mResolveComponentName = mCustomResolverComponentName;
7681            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7682                    mResolveComponentName);
7683        }
7684    }
7685
7686    private static String calculateBundledApkRoot(final String codePathString) {
7687        final File codePath = new File(codePathString);
7688        final File codeRoot;
7689        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7690            codeRoot = Environment.getRootDirectory();
7691        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7692            codeRoot = Environment.getOemDirectory();
7693        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7694            codeRoot = Environment.getVendorDirectory();
7695        } else {
7696            // Unrecognized code path; take its top real segment as the apk root:
7697            // e.g. /something/app/blah.apk => /something
7698            try {
7699                File f = codePath.getCanonicalFile();
7700                File parent = f.getParentFile();    // non-null because codePath is a file
7701                File tmp;
7702                while ((tmp = parent.getParentFile()) != null) {
7703                    f = parent;
7704                    parent = tmp;
7705                }
7706                codeRoot = f;
7707                Slog.w(TAG, "Unrecognized code path "
7708                        + codePath + " - using " + codeRoot);
7709            } catch (IOException e) {
7710                // Can't canonicalize the code path -- shenanigans?
7711                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7712                return Environment.getRootDirectory().getPath();
7713            }
7714        }
7715        return codeRoot.getPath();
7716    }
7717
7718    /**
7719     * Derive and set the location of native libraries for the given package,
7720     * which varies depending on where and how the package was installed.
7721     */
7722    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7723        final ApplicationInfo info = pkg.applicationInfo;
7724        final String codePath = pkg.codePath;
7725        final File codeFile = new File(codePath);
7726        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7727        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7728
7729        info.nativeLibraryRootDir = null;
7730        info.nativeLibraryRootRequiresIsa = false;
7731        info.nativeLibraryDir = null;
7732        info.secondaryNativeLibraryDir = null;
7733
7734        if (isApkFile(codeFile)) {
7735            // Monolithic install
7736            if (bundledApp) {
7737                // If "/system/lib64/apkname" exists, assume that is the per-package
7738                // native library directory to use; otherwise use "/system/lib/apkname".
7739                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7740                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7741                        getPrimaryInstructionSet(info));
7742
7743                // This is a bundled system app so choose the path based on the ABI.
7744                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7745                // is just the default path.
7746                final String apkName = deriveCodePathName(codePath);
7747                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7748                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7749                        apkName).getAbsolutePath();
7750
7751                if (info.secondaryCpuAbi != null) {
7752                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7753                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7754                            secondaryLibDir, apkName).getAbsolutePath();
7755                }
7756            } else if (asecApp) {
7757                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7758                        .getAbsolutePath();
7759            } else {
7760                final String apkName = deriveCodePathName(codePath);
7761                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7762                        .getAbsolutePath();
7763            }
7764
7765            info.nativeLibraryRootRequiresIsa = false;
7766            info.nativeLibraryDir = info.nativeLibraryRootDir;
7767        } else {
7768            // Cluster install
7769            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7770            info.nativeLibraryRootRequiresIsa = true;
7771
7772            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7773                    getPrimaryInstructionSet(info)).getAbsolutePath();
7774
7775            if (info.secondaryCpuAbi != null) {
7776                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7777                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7778            }
7779        }
7780    }
7781
7782    /**
7783     * Calculate the abis and roots for a bundled app. These can uniquely
7784     * be determined from the contents of the system partition, i.e whether
7785     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7786     * of this information, and instead assume that the system was built
7787     * sensibly.
7788     */
7789    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7790                                           PackageSetting pkgSetting) {
7791        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7792
7793        // If "/system/lib64/apkname" exists, assume that is the per-package
7794        // native library directory to use; otherwise use "/system/lib/apkname".
7795        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7796        setBundledAppAbi(pkg, apkRoot, apkName);
7797        // pkgSetting might be null during rescan following uninstall of updates
7798        // to a bundled app, so accommodate that possibility.  The settings in
7799        // that case will be established later from the parsed package.
7800        //
7801        // If the settings aren't null, sync them up with what we've just derived.
7802        // note that apkRoot isn't stored in the package settings.
7803        if (pkgSetting != null) {
7804            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7805            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7806        }
7807    }
7808
7809    /**
7810     * Deduces the ABI of a bundled app and sets the relevant fields on the
7811     * parsed pkg object.
7812     *
7813     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7814     *        under which system libraries are installed.
7815     * @param apkName the name of the installed package.
7816     */
7817    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7818        final File codeFile = new File(pkg.codePath);
7819
7820        final boolean has64BitLibs;
7821        final boolean has32BitLibs;
7822        if (isApkFile(codeFile)) {
7823            // Monolithic install
7824            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7825            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7826        } else {
7827            // Cluster install
7828            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7829            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7830                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7831                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7832                has64BitLibs = (new File(rootDir, isa)).exists();
7833            } else {
7834                has64BitLibs = false;
7835            }
7836            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7837                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7838                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7839                has32BitLibs = (new File(rootDir, isa)).exists();
7840            } else {
7841                has32BitLibs = false;
7842            }
7843        }
7844
7845        if (has64BitLibs && !has32BitLibs) {
7846            // The package has 64 bit libs, but not 32 bit libs. Its primary
7847            // ABI should be 64 bit. We can safely assume here that the bundled
7848            // native libraries correspond to the most preferred ABI in the list.
7849
7850            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7851            pkg.applicationInfo.secondaryCpuAbi = null;
7852        } else if (has32BitLibs && !has64BitLibs) {
7853            // The package has 32 bit libs but not 64 bit libs. Its primary
7854            // ABI should be 32 bit.
7855
7856            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7857            pkg.applicationInfo.secondaryCpuAbi = null;
7858        } else if (has32BitLibs && has64BitLibs) {
7859            // The application has both 64 and 32 bit bundled libraries. We check
7860            // here that the app declares multiArch support, and warn if it doesn't.
7861            //
7862            // We will be lenient here and record both ABIs. The primary will be the
7863            // ABI that's higher on the list, i.e, a device that's configured to prefer
7864            // 64 bit apps will see a 64 bit primary ABI,
7865
7866            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7867                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7868            }
7869
7870            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7871                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7872                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7873            } else {
7874                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7875                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7876            }
7877        } else {
7878            pkg.applicationInfo.primaryCpuAbi = null;
7879            pkg.applicationInfo.secondaryCpuAbi = null;
7880        }
7881    }
7882
7883    private void killApplication(String pkgName, int appId, String reason) {
7884        // Request the ActivityManager to kill the process(only for existing packages)
7885        // so that we do not end up in a confused state while the user is still using the older
7886        // version of the application while the new one gets installed.
7887        IActivityManager am = ActivityManagerNative.getDefault();
7888        if (am != null) {
7889            try {
7890                am.killApplicationWithAppId(pkgName, appId, reason);
7891            } catch (RemoteException e) {
7892            }
7893        }
7894    }
7895
7896    void removePackageLI(PackageSetting ps, boolean chatty) {
7897        if (DEBUG_INSTALL) {
7898            if (chatty)
7899                Log.d(TAG, "Removing package " + ps.name);
7900        }
7901
7902        // writer
7903        synchronized (mPackages) {
7904            mPackages.remove(ps.name);
7905            final PackageParser.Package pkg = ps.pkg;
7906            if (pkg != null) {
7907                cleanPackageDataStructuresLILPw(pkg, chatty);
7908            }
7909        }
7910    }
7911
7912    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7913        if (DEBUG_INSTALL) {
7914            if (chatty)
7915                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7916        }
7917
7918        // writer
7919        synchronized (mPackages) {
7920            mPackages.remove(pkg.applicationInfo.packageName);
7921            cleanPackageDataStructuresLILPw(pkg, chatty);
7922        }
7923    }
7924
7925    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7926        int N = pkg.providers.size();
7927        StringBuilder r = null;
7928        int i;
7929        for (i=0; i<N; i++) {
7930            PackageParser.Provider p = pkg.providers.get(i);
7931            mProviders.removeProvider(p);
7932            if (p.info.authority == null) {
7933
7934                /* There was another ContentProvider with this authority when
7935                 * this app was installed so this authority is null,
7936                 * Ignore it as we don't have to unregister the provider.
7937                 */
7938                continue;
7939            }
7940            String names[] = p.info.authority.split(";");
7941            for (int j = 0; j < names.length; j++) {
7942                if (mProvidersByAuthority.get(names[j]) == p) {
7943                    mProvidersByAuthority.remove(names[j]);
7944                    if (DEBUG_REMOVE) {
7945                        if (chatty)
7946                            Log.d(TAG, "Unregistered content provider: " + names[j]
7947                                    + ", className = " + p.info.name + ", isSyncable = "
7948                                    + p.info.isSyncable);
7949                    }
7950                }
7951            }
7952            if (DEBUG_REMOVE && chatty) {
7953                if (r == null) {
7954                    r = new StringBuilder(256);
7955                } else {
7956                    r.append(' ');
7957                }
7958                r.append(p.info.name);
7959            }
7960        }
7961        if (r != null) {
7962            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7963        }
7964
7965        N = pkg.services.size();
7966        r = null;
7967        for (i=0; i<N; i++) {
7968            PackageParser.Service s = pkg.services.get(i);
7969            mServices.removeService(s);
7970            if (chatty) {
7971                if (r == null) {
7972                    r = new StringBuilder(256);
7973                } else {
7974                    r.append(' ');
7975                }
7976                r.append(s.info.name);
7977            }
7978        }
7979        if (r != null) {
7980            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7981        }
7982
7983        N = pkg.receivers.size();
7984        r = null;
7985        for (i=0; i<N; i++) {
7986            PackageParser.Activity a = pkg.receivers.get(i);
7987            mReceivers.removeActivity(a, "receiver");
7988            if (DEBUG_REMOVE && chatty) {
7989                if (r == null) {
7990                    r = new StringBuilder(256);
7991                } else {
7992                    r.append(' ');
7993                }
7994                r.append(a.info.name);
7995            }
7996        }
7997        if (r != null) {
7998            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7999        }
8000
8001        N = pkg.activities.size();
8002        r = null;
8003        for (i=0; i<N; i++) {
8004            PackageParser.Activity a = pkg.activities.get(i);
8005            mActivities.removeActivity(a, "activity");
8006            if (DEBUG_REMOVE && chatty) {
8007                if (r == null) {
8008                    r = new StringBuilder(256);
8009                } else {
8010                    r.append(' ');
8011                }
8012                r.append(a.info.name);
8013            }
8014        }
8015        if (r != null) {
8016            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8017        }
8018
8019        N = pkg.permissions.size();
8020        r = null;
8021        for (i=0; i<N; i++) {
8022            PackageParser.Permission p = pkg.permissions.get(i);
8023            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8024            if (bp == null) {
8025                bp = mSettings.mPermissionTrees.get(p.info.name);
8026            }
8027            if (bp != null && bp.perm == p) {
8028                bp.perm = null;
8029                if (DEBUG_REMOVE && chatty) {
8030                    if (r == null) {
8031                        r = new StringBuilder(256);
8032                    } else {
8033                        r.append(' ');
8034                    }
8035                    r.append(p.info.name);
8036                }
8037            }
8038            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8039                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8040                if (appOpPerms != null) {
8041                    appOpPerms.remove(pkg.packageName);
8042                }
8043            }
8044        }
8045        if (r != null) {
8046            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8047        }
8048
8049        N = pkg.requestedPermissions.size();
8050        r = null;
8051        for (i=0; i<N; i++) {
8052            String perm = pkg.requestedPermissions.get(i);
8053            BasePermission bp = mSettings.mPermissions.get(perm);
8054            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8055                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8056                if (appOpPerms != null) {
8057                    appOpPerms.remove(pkg.packageName);
8058                    if (appOpPerms.isEmpty()) {
8059                        mAppOpPermissionPackages.remove(perm);
8060                    }
8061                }
8062            }
8063        }
8064        if (r != null) {
8065            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8066        }
8067
8068        N = pkg.instrumentation.size();
8069        r = null;
8070        for (i=0; i<N; i++) {
8071            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8072            mInstrumentation.remove(a.getComponentName());
8073            if (DEBUG_REMOVE && chatty) {
8074                if (r == null) {
8075                    r = new StringBuilder(256);
8076                } else {
8077                    r.append(' ');
8078                }
8079                r.append(a.info.name);
8080            }
8081        }
8082        if (r != null) {
8083            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8084        }
8085
8086        r = null;
8087        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8088            // Only system apps can hold shared libraries.
8089            if (pkg.libraryNames != null) {
8090                for (i=0; i<pkg.libraryNames.size(); i++) {
8091                    String name = pkg.libraryNames.get(i);
8092                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8093                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8094                        mSharedLibraries.remove(name);
8095                        if (DEBUG_REMOVE && chatty) {
8096                            if (r == null) {
8097                                r = new StringBuilder(256);
8098                            } else {
8099                                r.append(' ');
8100                            }
8101                            r.append(name);
8102                        }
8103                    }
8104                }
8105            }
8106        }
8107        if (r != null) {
8108            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8109        }
8110    }
8111
8112    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8113        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8114            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8115                return true;
8116            }
8117        }
8118        return false;
8119    }
8120
8121    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8122    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8123    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8124
8125    private void updatePermissionsLPw(String changingPkg,
8126            PackageParser.Package pkgInfo, int flags) {
8127        // Make sure there are no dangling permission trees.
8128        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8129        while (it.hasNext()) {
8130            final BasePermission bp = it.next();
8131            if (bp.packageSetting == null) {
8132                // We may not yet have parsed the package, so just see if
8133                // we still know about its settings.
8134                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8135            }
8136            if (bp.packageSetting == null) {
8137                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8138                        + " from package " + bp.sourcePackage);
8139                it.remove();
8140            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8141                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8142                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8143                            + " from package " + bp.sourcePackage);
8144                    flags |= UPDATE_PERMISSIONS_ALL;
8145                    it.remove();
8146                }
8147            }
8148        }
8149
8150        // Make sure all dynamic permissions have been assigned to a package,
8151        // and make sure there are no dangling permissions.
8152        it = mSettings.mPermissions.values().iterator();
8153        while (it.hasNext()) {
8154            final BasePermission bp = it.next();
8155            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8156                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8157                        + bp.name + " pkg=" + bp.sourcePackage
8158                        + " info=" + bp.pendingInfo);
8159                if (bp.packageSetting == null && bp.pendingInfo != null) {
8160                    final BasePermission tree = findPermissionTreeLP(bp.name);
8161                    if (tree != null && tree.perm != null) {
8162                        bp.packageSetting = tree.packageSetting;
8163                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8164                                new PermissionInfo(bp.pendingInfo));
8165                        bp.perm.info.packageName = tree.perm.info.packageName;
8166                        bp.perm.info.name = bp.name;
8167                        bp.uid = tree.uid;
8168                    }
8169                }
8170            }
8171            if (bp.packageSetting == null) {
8172                // We may not yet have parsed the package, so just see if
8173                // we still know about its settings.
8174                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8175            }
8176            if (bp.packageSetting == null) {
8177                Slog.w(TAG, "Removing dangling permission: " + bp.name
8178                        + " from package " + bp.sourcePackage);
8179                it.remove();
8180            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8181                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8182                    Slog.i(TAG, "Removing old permission: " + bp.name
8183                            + " from package " + bp.sourcePackage);
8184                    flags |= UPDATE_PERMISSIONS_ALL;
8185                    it.remove();
8186                }
8187            }
8188        }
8189
8190        // Now update the permissions for all packages, in particular
8191        // replace the granted permissions of the system packages.
8192        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8193            for (PackageParser.Package pkg : mPackages.values()) {
8194                if (pkg != pkgInfo) {
8195                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8196                            changingPkg);
8197                }
8198            }
8199        }
8200
8201        if (pkgInfo != null) {
8202            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8203        }
8204    }
8205
8206    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8207            String packageOfInterest) {
8208        // IMPORTANT: There are two types of permissions: install and runtime.
8209        // Install time permissions are granted when the app is installed to
8210        // all device users and users added in the future. Runtime permissions
8211        // are granted at runtime explicitly to specific users. Normal and signature
8212        // protected permissions are install time permissions. Dangerous permissions
8213        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8214        // otherwise they are runtime permissions. This function does not manage
8215        // runtime permissions except for the case an app targeting Lollipop MR1
8216        // being upgraded to target a newer SDK, in which case dangerous permissions
8217        // are transformed from install time to runtime ones.
8218
8219        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8220        if (ps == null) {
8221            return;
8222        }
8223
8224        PermissionsState permissionsState = ps.getPermissionsState();
8225        PermissionsState origPermissions = permissionsState;
8226
8227        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8228
8229        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8230
8231        boolean changedInstallPermission = false;
8232
8233        if (replace) {
8234            ps.installPermissionsFixed = false;
8235            if (!ps.isSharedUser()) {
8236                origPermissions = new PermissionsState(permissionsState);
8237                permissionsState.reset();
8238            }
8239        }
8240
8241        permissionsState.setGlobalGids(mGlobalGids);
8242
8243        final int N = pkg.requestedPermissions.size();
8244        for (int i=0; i<N; i++) {
8245            final String name = pkg.requestedPermissions.get(i);
8246            final BasePermission bp = mSettings.mPermissions.get(name);
8247
8248            if (DEBUG_INSTALL) {
8249                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8250            }
8251
8252            if (bp == null || bp.packageSetting == null) {
8253                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8254                    Slog.w(TAG, "Unknown permission " + name
8255                            + " in package " + pkg.packageName);
8256                }
8257                continue;
8258            }
8259
8260            final String perm = bp.name;
8261            boolean allowedSig = false;
8262            int grant = GRANT_DENIED;
8263
8264            // Keep track of app op permissions.
8265            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8266                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8267                if (pkgs == null) {
8268                    pkgs = new ArraySet<>();
8269                    mAppOpPermissionPackages.put(bp.name, pkgs);
8270                }
8271                pkgs.add(pkg.packageName);
8272            }
8273
8274            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8275            switch (level) {
8276                case PermissionInfo.PROTECTION_NORMAL: {
8277                    // For all apps normal permissions are install time ones.
8278                    grant = GRANT_INSTALL;
8279                } break;
8280
8281                case PermissionInfo.PROTECTION_DANGEROUS: {
8282                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8283                        // For legacy apps dangerous permissions are install time ones.
8284                        grant = GRANT_INSTALL_LEGACY;
8285                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8286                        // For legacy apps that became modern, install becomes runtime.
8287                        grant = GRANT_UPGRADE;
8288                    } else {
8289                        // For modern apps keep runtime permissions unchanged.
8290                        grant = GRANT_RUNTIME;
8291                    }
8292                } break;
8293
8294                case PermissionInfo.PROTECTION_SIGNATURE: {
8295                    // For all apps signature permissions are install time ones.
8296                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8297                    if (allowedSig) {
8298                        grant = GRANT_INSTALL;
8299                    }
8300                } break;
8301            }
8302
8303            if (DEBUG_INSTALL) {
8304                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8305            }
8306
8307            if (grant != GRANT_DENIED) {
8308                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8309                    // If this is an existing, non-system package, then
8310                    // we can't add any new permissions to it.
8311                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8312                        // Except...  if this is a permission that was added
8313                        // to the platform (note: need to only do this when
8314                        // updating the platform).
8315                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8316                            grant = GRANT_DENIED;
8317                        }
8318                    }
8319                }
8320
8321                switch (grant) {
8322                    case GRANT_INSTALL: {
8323                        // Revoke this as runtime permission to handle the case of
8324                        // a runtime permission being downgraded to an install one.
8325                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8326                            if (origPermissions.getRuntimePermissionState(
8327                                    bp.name, userId) != null) {
8328                                // Revoke the runtime permission and clear the flags.
8329                                origPermissions.revokeRuntimePermission(bp, userId);
8330                                origPermissions.updatePermissionFlags(bp, userId,
8331                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8332                                // If we revoked a permission permission, we have to write.
8333                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8334                                        changedRuntimePermissionUserIds, userId);
8335                            }
8336                        }
8337                        // Grant an install permission.
8338                        if (permissionsState.grantInstallPermission(bp) !=
8339                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8340                            changedInstallPermission = true;
8341                        }
8342                    } break;
8343
8344                    case GRANT_INSTALL_LEGACY: {
8345                        // Grant an install permission.
8346                        if (permissionsState.grantInstallPermission(bp) !=
8347                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8348                            changedInstallPermission = true;
8349                        }
8350                    } break;
8351
8352                    case GRANT_RUNTIME: {
8353                        // Grant previously granted runtime permissions.
8354                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8355                            PermissionState permissionState = origPermissions
8356                                    .getRuntimePermissionState(bp.name, userId);
8357                            final int flags = permissionState != null
8358                                    ? permissionState.getFlags() : 0;
8359                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8360                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8361                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8362                                    // If we cannot put the permission as it was, we have to write.
8363                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8364                                            changedRuntimePermissionUserIds, userId);
8365                                }
8366                            }
8367                            // Propagate the permission flags.
8368                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8369                        }
8370                    } break;
8371
8372                    case GRANT_UPGRADE: {
8373                        // Grant runtime permissions for a previously held install permission.
8374                        PermissionState permissionState = origPermissions
8375                                .getInstallPermissionState(bp.name);
8376                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8377
8378                        if (origPermissions.revokeInstallPermission(bp)
8379                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8380                            // We will be transferring the permission flags, so clear them.
8381                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8382                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8383                            changedInstallPermission = true;
8384                        }
8385
8386                        // If the permission is not to be promoted to runtime we ignore it and
8387                        // also its other flags as they are not applicable to install permissions.
8388                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8389                            for (int userId : currentUserIds) {
8390                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8391                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8392                                    // Transfer the permission flags.
8393                                    permissionsState.updatePermissionFlags(bp, userId,
8394                                            flags, flags);
8395                                    // If we granted the permission, we have to write.
8396                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8397                                            changedRuntimePermissionUserIds, userId);
8398                                }
8399                            }
8400                        }
8401                    } break;
8402
8403                    default: {
8404                        if (packageOfInterest == null
8405                                || packageOfInterest.equals(pkg.packageName)) {
8406                            Slog.w(TAG, "Not granting permission " + perm
8407                                    + " to package " + pkg.packageName
8408                                    + " because it was previously installed without");
8409                        }
8410                    } break;
8411                }
8412            } else {
8413                if (permissionsState.revokeInstallPermission(bp) !=
8414                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8415                    // Also drop the permission flags.
8416                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8417                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8418                    changedInstallPermission = true;
8419                    Slog.i(TAG, "Un-granting permission " + perm
8420                            + " from package " + pkg.packageName
8421                            + " (protectionLevel=" + bp.protectionLevel
8422                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8423                            + ")");
8424                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8425                    // Don't print warning for app op permissions, since it is fine for them
8426                    // not to be granted, there is a UI for the user to decide.
8427                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8428                        Slog.w(TAG, "Not granting permission " + perm
8429                                + " to package " + pkg.packageName
8430                                + " (protectionLevel=" + bp.protectionLevel
8431                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8432                                + ")");
8433                    }
8434                }
8435            }
8436        }
8437
8438        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8439                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8440            // This is the first that we have heard about this package, so the
8441            // permissions we have now selected are fixed until explicitly
8442            // changed.
8443            ps.installPermissionsFixed = true;
8444        }
8445
8446        // Persist the runtime permissions state for users with changes.
8447        for (int userId : changedRuntimePermissionUserIds) {
8448            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8449        }
8450    }
8451
8452    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8453        boolean allowed = false;
8454        final int NP = PackageParser.NEW_PERMISSIONS.length;
8455        for (int ip=0; ip<NP; ip++) {
8456            final PackageParser.NewPermissionInfo npi
8457                    = PackageParser.NEW_PERMISSIONS[ip];
8458            if (npi.name.equals(perm)
8459                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8460                allowed = true;
8461                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8462                        + pkg.packageName);
8463                break;
8464            }
8465        }
8466        return allowed;
8467    }
8468
8469    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8470            BasePermission bp, PermissionsState origPermissions) {
8471        boolean allowed;
8472        allowed = (compareSignatures(
8473                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8474                        == PackageManager.SIGNATURE_MATCH)
8475                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8476                        == PackageManager.SIGNATURE_MATCH);
8477        if (!allowed && (bp.protectionLevel
8478                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8479            if (isSystemApp(pkg)) {
8480                // For updated system applications, a system permission
8481                // is granted only if it had been defined by the original application.
8482                if (pkg.isUpdatedSystemApp()) {
8483                    final PackageSetting sysPs = mSettings
8484                            .getDisabledSystemPkgLPr(pkg.packageName);
8485                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8486                        // If the original was granted this permission, we take
8487                        // that grant decision as read and propagate it to the
8488                        // update.
8489                        if (sysPs.isPrivileged()) {
8490                            allowed = true;
8491                        }
8492                    } else {
8493                        // The system apk may have been updated with an older
8494                        // version of the one on the data partition, but which
8495                        // granted a new system permission that it didn't have
8496                        // before.  In this case we do want to allow the app to
8497                        // now get the new permission if the ancestral apk is
8498                        // privileged to get it.
8499                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8500                            for (int j=0;
8501                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8502                                if (perm.equals(
8503                                        sysPs.pkg.requestedPermissions.get(j))) {
8504                                    allowed = true;
8505                                    break;
8506                                }
8507                            }
8508                        }
8509                    }
8510                } else {
8511                    allowed = isPrivilegedApp(pkg);
8512                }
8513            }
8514        }
8515        if (!allowed) {
8516            if (!allowed && (bp.protectionLevel
8517                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8518                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8519                // If this was a previously normal/dangerous permission that got moved
8520                // to a system permission as part of the runtime permission redesign, then
8521                // we still want to blindly grant it to old apps.
8522                allowed = true;
8523            }
8524            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8525                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8526                // If this permission is to be granted to the system installer and
8527                // this app is an installer, then it gets the permission.
8528                allowed = true;
8529            }
8530            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8531                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8532                // If this permission is to be granted to the system verifier and
8533                // this app is a verifier, then it gets the permission.
8534                allowed = true;
8535            }
8536            if (!allowed && (bp.protectionLevel
8537                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8538                    && isSystemApp(pkg)) {
8539                // Any pre-installed system app is allowed to get this permission.
8540                allowed = true;
8541            }
8542            if (!allowed && (bp.protectionLevel
8543                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8544                // For development permissions, a development permission
8545                // is granted only if it was already granted.
8546                allowed = origPermissions.hasInstallPermission(perm);
8547            }
8548        }
8549        return allowed;
8550    }
8551
8552    final class ActivityIntentResolver
8553            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8554        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8555                boolean defaultOnly, int userId) {
8556            if (!sUserManager.exists(userId)) return null;
8557            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8558            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8559        }
8560
8561        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8562                int userId) {
8563            if (!sUserManager.exists(userId)) return null;
8564            mFlags = flags;
8565            return super.queryIntent(intent, resolvedType,
8566                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8567        }
8568
8569        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8570                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8571            if (!sUserManager.exists(userId)) return null;
8572            if (packageActivities == null) {
8573                return null;
8574            }
8575            mFlags = flags;
8576            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8577            final int N = packageActivities.size();
8578            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8579                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8580
8581            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8582            for (int i = 0; i < N; ++i) {
8583                intentFilters = packageActivities.get(i).intents;
8584                if (intentFilters != null && intentFilters.size() > 0) {
8585                    PackageParser.ActivityIntentInfo[] array =
8586                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8587                    intentFilters.toArray(array);
8588                    listCut.add(array);
8589                }
8590            }
8591            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8592        }
8593
8594        public final void addActivity(PackageParser.Activity a, String type) {
8595            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8596            mActivities.put(a.getComponentName(), a);
8597            if (DEBUG_SHOW_INFO)
8598                Log.v(
8599                TAG, "  " + type + " " +
8600                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8601            if (DEBUG_SHOW_INFO)
8602                Log.v(TAG, "    Class=" + a.info.name);
8603            final int NI = a.intents.size();
8604            for (int j=0; j<NI; j++) {
8605                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8606                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8607                    intent.setPriority(0);
8608                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8609                            + a.className + " with priority > 0, forcing to 0");
8610                }
8611                if (DEBUG_SHOW_INFO) {
8612                    Log.v(TAG, "    IntentFilter:");
8613                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8614                }
8615                if (!intent.debugCheck()) {
8616                    Log.w(TAG, "==> For Activity " + a.info.name);
8617                }
8618                addFilter(intent);
8619            }
8620        }
8621
8622        public final void removeActivity(PackageParser.Activity a, String type) {
8623            mActivities.remove(a.getComponentName());
8624            if (DEBUG_SHOW_INFO) {
8625                Log.v(TAG, "  " + type + " "
8626                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8627                                : a.info.name) + ":");
8628                Log.v(TAG, "    Class=" + a.info.name);
8629            }
8630            final int NI = a.intents.size();
8631            for (int j=0; j<NI; j++) {
8632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8633                if (DEBUG_SHOW_INFO) {
8634                    Log.v(TAG, "    IntentFilter:");
8635                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8636                }
8637                removeFilter(intent);
8638            }
8639        }
8640
8641        @Override
8642        protected boolean allowFilterResult(
8643                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8644            ActivityInfo filterAi = filter.activity.info;
8645            for (int i=dest.size()-1; i>=0; i--) {
8646                ActivityInfo destAi = dest.get(i).activityInfo;
8647                if (destAi.name == filterAi.name
8648                        && destAi.packageName == filterAi.packageName) {
8649                    return false;
8650                }
8651            }
8652            return true;
8653        }
8654
8655        @Override
8656        protected ActivityIntentInfo[] newArray(int size) {
8657            return new ActivityIntentInfo[size];
8658        }
8659
8660        @Override
8661        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8662            if (!sUserManager.exists(userId)) return true;
8663            PackageParser.Package p = filter.activity.owner;
8664            if (p != null) {
8665                PackageSetting ps = (PackageSetting)p.mExtras;
8666                if (ps != null) {
8667                    // System apps are never considered stopped for purposes of
8668                    // filtering, because there may be no way for the user to
8669                    // actually re-launch them.
8670                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8671                            && ps.getStopped(userId);
8672                }
8673            }
8674            return false;
8675        }
8676
8677        @Override
8678        protected boolean isPackageForFilter(String packageName,
8679                PackageParser.ActivityIntentInfo info) {
8680            return packageName.equals(info.activity.owner.packageName);
8681        }
8682
8683        @Override
8684        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8685                int match, int userId) {
8686            if (!sUserManager.exists(userId)) return null;
8687            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8688                return null;
8689            }
8690            final PackageParser.Activity activity = info.activity;
8691            if (mSafeMode && (activity.info.applicationInfo.flags
8692                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8693                return null;
8694            }
8695            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8696            if (ps == null) {
8697                return null;
8698            }
8699            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8700                    ps.readUserState(userId), userId);
8701            if (ai == null) {
8702                return null;
8703            }
8704            final ResolveInfo res = new ResolveInfo();
8705            res.activityInfo = ai;
8706            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8707                res.filter = info;
8708            }
8709            if (info != null) {
8710                res.handleAllWebDataURI = info.handleAllWebDataURI();
8711            }
8712            res.priority = info.getPriority();
8713            res.preferredOrder = activity.owner.mPreferredOrder;
8714            //System.out.println("Result: " + res.activityInfo.className +
8715            //                   " = " + res.priority);
8716            res.match = match;
8717            res.isDefault = info.hasDefault;
8718            res.labelRes = info.labelRes;
8719            res.nonLocalizedLabel = info.nonLocalizedLabel;
8720            if (userNeedsBadging(userId)) {
8721                res.noResourceId = true;
8722            } else {
8723                res.icon = info.icon;
8724            }
8725            res.iconResourceId = info.icon;
8726            res.system = res.activityInfo.applicationInfo.isSystemApp();
8727            return res;
8728        }
8729
8730        @Override
8731        protected void sortResults(List<ResolveInfo> results) {
8732            Collections.sort(results, mResolvePrioritySorter);
8733        }
8734
8735        @Override
8736        protected void dumpFilter(PrintWriter out, String prefix,
8737                PackageParser.ActivityIntentInfo filter) {
8738            out.print(prefix); out.print(
8739                    Integer.toHexString(System.identityHashCode(filter.activity)));
8740                    out.print(' ');
8741                    filter.activity.printComponentShortName(out);
8742                    out.print(" filter ");
8743                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8744        }
8745
8746        @Override
8747        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8748            return filter.activity;
8749        }
8750
8751        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8752            PackageParser.Activity activity = (PackageParser.Activity)label;
8753            out.print(prefix); out.print(
8754                    Integer.toHexString(System.identityHashCode(activity)));
8755                    out.print(' ');
8756                    activity.printComponentShortName(out);
8757            if (count > 1) {
8758                out.print(" ("); out.print(count); out.print(" filters)");
8759            }
8760            out.println();
8761        }
8762
8763//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8764//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8765//            final List<ResolveInfo> retList = Lists.newArrayList();
8766//            while (i.hasNext()) {
8767//                final ResolveInfo resolveInfo = i.next();
8768//                if (isEnabledLP(resolveInfo.activityInfo)) {
8769//                    retList.add(resolveInfo);
8770//                }
8771//            }
8772//            return retList;
8773//        }
8774
8775        // Keys are String (activity class name), values are Activity.
8776        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8777                = new ArrayMap<ComponentName, PackageParser.Activity>();
8778        private int mFlags;
8779    }
8780
8781    private final class ServiceIntentResolver
8782            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8783        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8784                boolean defaultOnly, int userId) {
8785            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8786            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8787        }
8788
8789        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8790                int userId) {
8791            if (!sUserManager.exists(userId)) return null;
8792            mFlags = flags;
8793            return super.queryIntent(intent, resolvedType,
8794                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8795        }
8796
8797        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8798                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8799            if (!sUserManager.exists(userId)) return null;
8800            if (packageServices == null) {
8801                return null;
8802            }
8803            mFlags = flags;
8804            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8805            final int N = packageServices.size();
8806            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8807                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8808
8809            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8810            for (int i = 0; i < N; ++i) {
8811                intentFilters = packageServices.get(i).intents;
8812                if (intentFilters != null && intentFilters.size() > 0) {
8813                    PackageParser.ServiceIntentInfo[] array =
8814                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8815                    intentFilters.toArray(array);
8816                    listCut.add(array);
8817                }
8818            }
8819            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8820        }
8821
8822        public final void addService(PackageParser.Service s) {
8823            mServices.put(s.getComponentName(), s);
8824            if (DEBUG_SHOW_INFO) {
8825                Log.v(TAG, "  "
8826                        + (s.info.nonLocalizedLabel != null
8827                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8828                Log.v(TAG, "    Class=" + s.info.name);
8829            }
8830            final int NI = s.intents.size();
8831            int j;
8832            for (j=0; j<NI; j++) {
8833                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8834                if (DEBUG_SHOW_INFO) {
8835                    Log.v(TAG, "    IntentFilter:");
8836                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8837                }
8838                if (!intent.debugCheck()) {
8839                    Log.w(TAG, "==> For Service " + s.info.name);
8840                }
8841                addFilter(intent);
8842            }
8843        }
8844
8845        public final void removeService(PackageParser.Service s) {
8846            mServices.remove(s.getComponentName());
8847            if (DEBUG_SHOW_INFO) {
8848                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8849                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8850                Log.v(TAG, "    Class=" + s.info.name);
8851            }
8852            final int NI = s.intents.size();
8853            int j;
8854            for (j=0; j<NI; j++) {
8855                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8856                if (DEBUG_SHOW_INFO) {
8857                    Log.v(TAG, "    IntentFilter:");
8858                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8859                }
8860                removeFilter(intent);
8861            }
8862        }
8863
8864        @Override
8865        protected boolean allowFilterResult(
8866                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8867            ServiceInfo filterSi = filter.service.info;
8868            for (int i=dest.size()-1; i>=0; i--) {
8869                ServiceInfo destAi = dest.get(i).serviceInfo;
8870                if (destAi.name == filterSi.name
8871                        && destAi.packageName == filterSi.packageName) {
8872                    return false;
8873                }
8874            }
8875            return true;
8876        }
8877
8878        @Override
8879        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8880            return new PackageParser.ServiceIntentInfo[size];
8881        }
8882
8883        @Override
8884        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8885            if (!sUserManager.exists(userId)) return true;
8886            PackageParser.Package p = filter.service.owner;
8887            if (p != null) {
8888                PackageSetting ps = (PackageSetting)p.mExtras;
8889                if (ps != null) {
8890                    // System apps are never considered stopped for purposes of
8891                    // filtering, because there may be no way for the user to
8892                    // actually re-launch them.
8893                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8894                            && ps.getStopped(userId);
8895                }
8896            }
8897            return false;
8898        }
8899
8900        @Override
8901        protected boolean isPackageForFilter(String packageName,
8902                PackageParser.ServiceIntentInfo info) {
8903            return packageName.equals(info.service.owner.packageName);
8904        }
8905
8906        @Override
8907        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8908                int match, int userId) {
8909            if (!sUserManager.exists(userId)) return null;
8910            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8911            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8912                return null;
8913            }
8914            final PackageParser.Service service = info.service;
8915            if (mSafeMode && (service.info.applicationInfo.flags
8916                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8917                return null;
8918            }
8919            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8920            if (ps == null) {
8921                return null;
8922            }
8923            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8924                    ps.readUserState(userId), userId);
8925            if (si == null) {
8926                return null;
8927            }
8928            final ResolveInfo res = new ResolveInfo();
8929            res.serviceInfo = si;
8930            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8931                res.filter = filter;
8932            }
8933            res.priority = info.getPriority();
8934            res.preferredOrder = service.owner.mPreferredOrder;
8935            res.match = match;
8936            res.isDefault = info.hasDefault;
8937            res.labelRes = info.labelRes;
8938            res.nonLocalizedLabel = info.nonLocalizedLabel;
8939            res.icon = info.icon;
8940            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8941            return res;
8942        }
8943
8944        @Override
8945        protected void sortResults(List<ResolveInfo> results) {
8946            Collections.sort(results, mResolvePrioritySorter);
8947        }
8948
8949        @Override
8950        protected void dumpFilter(PrintWriter out, String prefix,
8951                PackageParser.ServiceIntentInfo filter) {
8952            out.print(prefix); out.print(
8953                    Integer.toHexString(System.identityHashCode(filter.service)));
8954                    out.print(' ');
8955                    filter.service.printComponentShortName(out);
8956                    out.print(" filter ");
8957                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8958        }
8959
8960        @Override
8961        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8962            return filter.service;
8963        }
8964
8965        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8966            PackageParser.Service service = (PackageParser.Service)label;
8967            out.print(prefix); out.print(
8968                    Integer.toHexString(System.identityHashCode(service)));
8969                    out.print(' ');
8970                    service.printComponentShortName(out);
8971            if (count > 1) {
8972                out.print(" ("); out.print(count); out.print(" filters)");
8973            }
8974            out.println();
8975        }
8976
8977//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8978//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8979//            final List<ResolveInfo> retList = Lists.newArrayList();
8980//            while (i.hasNext()) {
8981//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8982//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8983//                    retList.add(resolveInfo);
8984//                }
8985//            }
8986//            return retList;
8987//        }
8988
8989        // Keys are String (activity class name), values are Activity.
8990        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8991                = new ArrayMap<ComponentName, PackageParser.Service>();
8992        private int mFlags;
8993    };
8994
8995    private final class ProviderIntentResolver
8996            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8997        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8998                boolean defaultOnly, int userId) {
8999            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9000            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9001        }
9002
9003        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9004                int userId) {
9005            if (!sUserManager.exists(userId))
9006                return null;
9007            mFlags = flags;
9008            return super.queryIntent(intent, resolvedType,
9009                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9010        }
9011
9012        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9013                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9014            if (!sUserManager.exists(userId))
9015                return null;
9016            if (packageProviders == null) {
9017                return null;
9018            }
9019            mFlags = flags;
9020            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9021            final int N = packageProviders.size();
9022            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9023                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9024
9025            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9026            for (int i = 0; i < N; ++i) {
9027                intentFilters = packageProviders.get(i).intents;
9028                if (intentFilters != null && intentFilters.size() > 0) {
9029                    PackageParser.ProviderIntentInfo[] array =
9030                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9031                    intentFilters.toArray(array);
9032                    listCut.add(array);
9033                }
9034            }
9035            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9036        }
9037
9038        public final void addProvider(PackageParser.Provider p) {
9039            if (mProviders.containsKey(p.getComponentName())) {
9040                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9041                return;
9042            }
9043
9044            mProviders.put(p.getComponentName(), p);
9045            if (DEBUG_SHOW_INFO) {
9046                Log.v(TAG, "  "
9047                        + (p.info.nonLocalizedLabel != null
9048                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9049                Log.v(TAG, "    Class=" + p.info.name);
9050            }
9051            final int NI = p.intents.size();
9052            int j;
9053            for (j = 0; j < NI; j++) {
9054                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9055                if (DEBUG_SHOW_INFO) {
9056                    Log.v(TAG, "    IntentFilter:");
9057                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9058                }
9059                if (!intent.debugCheck()) {
9060                    Log.w(TAG, "==> For Provider " + p.info.name);
9061                }
9062                addFilter(intent);
9063            }
9064        }
9065
9066        public final void removeProvider(PackageParser.Provider p) {
9067            mProviders.remove(p.getComponentName());
9068            if (DEBUG_SHOW_INFO) {
9069                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9070                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9071                Log.v(TAG, "    Class=" + p.info.name);
9072            }
9073            final int NI = p.intents.size();
9074            int j;
9075            for (j = 0; j < NI; j++) {
9076                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9077                if (DEBUG_SHOW_INFO) {
9078                    Log.v(TAG, "    IntentFilter:");
9079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9080                }
9081                removeFilter(intent);
9082            }
9083        }
9084
9085        @Override
9086        protected boolean allowFilterResult(
9087                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9088            ProviderInfo filterPi = filter.provider.info;
9089            for (int i = dest.size() - 1; i >= 0; i--) {
9090                ProviderInfo destPi = dest.get(i).providerInfo;
9091                if (destPi.name == filterPi.name
9092                        && destPi.packageName == filterPi.packageName) {
9093                    return false;
9094                }
9095            }
9096            return true;
9097        }
9098
9099        @Override
9100        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9101            return new PackageParser.ProviderIntentInfo[size];
9102        }
9103
9104        @Override
9105        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9106            if (!sUserManager.exists(userId))
9107                return true;
9108            PackageParser.Package p = filter.provider.owner;
9109            if (p != null) {
9110                PackageSetting ps = (PackageSetting) p.mExtras;
9111                if (ps != null) {
9112                    // System apps are never considered stopped for purposes of
9113                    // filtering, because there may be no way for the user to
9114                    // actually re-launch them.
9115                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9116                            && ps.getStopped(userId);
9117                }
9118            }
9119            return false;
9120        }
9121
9122        @Override
9123        protected boolean isPackageForFilter(String packageName,
9124                PackageParser.ProviderIntentInfo info) {
9125            return packageName.equals(info.provider.owner.packageName);
9126        }
9127
9128        @Override
9129        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9130                int match, int userId) {
9131            if (!sUserManager.exists(userId))
9132                return null;
9133            final PackageParser.ProviderIntentInfo info = filter;
9134            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9135                return null;
9136            }
9137            final PackageParser.Provider provider = info.provider;
9138            if (mSafeMode && (provider.info.applicationInfo.flags
9139                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9140                return null;
9141            }
9142            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9143            if (ps == null) {
9144                return null;
9145            }
9146            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9147                    ps.readUserState(userId), userId);
9148            if (pi == null) {
9149                return null;
9150            }
9151            final ResolveInfo res = new ResolveInfo();
9152            res.providerInfo = pi;
9153            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9154                res.filter = filter;
9155            }
9156            res.priority = info.getPriority();
9157            res.preferredOrder = provider.owner.mPreferredOrder;
9158            res.match = match;
9159            res.isDefault = info.hasDefault;
9160            res.labelRes = info.labelRes;
9161            res.nonLocalizedLabel = info.nonLocalizedLabel;
9162            res.icon = info.icon;
9163            res.system = res.providerInfo.applicationInfo.isSystemApp();
9164            return res;
9165        }
9166
9167        @Override
9168        protected void sortResults(List<ResolveInfo> results) {
9169            Collections.sort(results, mResolvePrioritySorter);
9170        }
9171
9172        @Override
9173        protected void dumpFilter(PrintWriter out, String prefix,
9174                PackageParser.ProviderIntentInfo filter) {
9175            out.print(prefix);
9176            out.print(
9177                    Integer.toHexString(System.identityHashCode(filter.provider)));
9178            out.print(' ');
9179            filter.provider.printComponentShortName(out);
9180            out.print(" filter ");
9181            out.println(Integer.toHexString(System.identityHashCode(filter)));
9182        }
9183
9184        @Override
9185        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9186            return filter.provider;
9187        }
9188
9189        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9190            PackageParser.Provider provider = (PackageParser.Provider)label;
9191            out.print(prefix); out.print(
9192                    Integer.toHexString(System.identityHashCode(provider)));
9193                    out.print(' ');
9194                    provider.printComponentShortName(out);
9195            if (count > 1) {
9196                out.print(" ("); out.print(count); out.print(" filters)");
9197            }
9198            out.println();
9199        }
9200
9201        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9202                = new ArrayMap<ComponentName, PackageParser.Provider>();
9203        private int mFlags;
9204    };
9205
9206    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9207            new Comparator<ResolveInfo>() {
9208        public int compare(ResolveInfo r1, ResolveInfo r2) {
9209            int v1 = r1.priority;
9210            int v2 = r2.priority;
9211            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9212            if (v1 != v2) {
9213                return (v1 > v2) ? -1 : 1;
9214            }
9215            v1 = r1.preferredOrder;
9216            v2 = r2.preferredOrder;
9217            if (v1 != v2) {
9218                return (v1 > v2) ? -1 : 1;
9219            }
9220            if (r1.isDefault != r2.isDefault) {
9221                return r1.isDefault ? -1 : 1;
9222            }
9223            v1 = r1.match;
9224            v2 = r2.match;
9225            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9226            if (v1 != v2) {
9227                return (v1 > v2) ? -1 : 1;
9228            }
9229            if (r1.system != r2.system) {
9230                return r1.system ? -1 : 1;
9231            }
9232            return 0;
9233        }
9234    };
9235
9236    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9237            new Comparator<ProviderInfo>() {
9238        public int compare(ProviderInfo p1, ProviderInfo p2) {
9239            final int v1 = p1.initOrder;
9240            final int v2 = p2.initOrder;
9241            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9242        }
9243    };
9244
9245    final void sendPackageBroadcast(final String action, final String pkg,
9246            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9247            final int[] userIds) {
9248        mHandler.post(new Runnable() {
9249            @Override
9250            public void run() {
9251                try {
9252                    final IActivityManager am = ActivityManagerNative.getDefault();
9253                    if (am == null) return;
9254                    final int[] resolvedUserIds;
9255                    if (userIds == null) {
9256                        resolvedUserIds = am.getRunningUserIds();
9257                    } else {
9258                        resolvedUserIds = userIds;
9259                    }
9260                    for (int id : resolvedUserIds) {
9261                        final Intent intent = new Intent(action,
9262                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9263                        if (extras != null) {
9264                            intent.putExtras(extras);
9265                        }
9266                        if (targetPkg != null) {
9267                            intent.setPackage(targetPkg);
9268                        }
9269                        // Modify the UID when posting to other users
9270                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9271                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9272                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9273                            intent.putExtra(Intent.EXTRA_UID, uid);
9274                        }
9275                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9276                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9277                        if (DEBUG_BROADCASTS) {
9278                            RuntimeException here = new RuntimeException("here");
9279                            here.fillInStackTrace();
9280                            Slog.d(TAG, "Sending to user " + id + ": "
9281                                    + intent.toShortString(false, true, false, false)
9282                                    + " " + intent.getExtras(), here);
9283                        }
9284                        am.broadcastIntent(null, intent, null, finishedReceiver,
9285                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9286                                null, finishedReceiver != null, false, id);
9287                    }
9288                } catch (RemoteException ex) {
9289                }
9290            }
9291        });
9292    }
9293
9294    /**
9295     * Check if the external storage media is available. This is true if there
9296     * is a mounted external storage medium or if the external storage is
9297     * emulated.
9298     */
9299    private boolean isExternalMediaAvailable() {
9300        return mMediaMounted || Environment.isExternalStorageEmulated();
9301    }
9302
9303    @Override
9304    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9305        // writer
9306        synchronized (mPackages) {
9307            if (!isExternalMediaAvailable()) {
9308                // If the external storage is no longer mounted at this point,
9309                // the caller may not have been able to delete all of this
9310                // packages files and can not delete any more.  Bail.
9311                return null;
9312            }
9313            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9314            if (lastPackage != null) {
9315                pkgs.remove(lastPackage);
9316            }
9317            if (pkgs.size() > 0) {
9318                return pkgs.get(0);
9319            }
9320        }
9321        return null;
9322    }
9323
9324    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9325        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9326                userId, andCode ? 1 : 0, packageName);
9327        if (mSystemReady) {
9328            msg.sendToTarget();
9329        } else {
9330            if (mPostSystemReadyMessages == null) {
9331                mPostSystemReadyMessages = new ArrayList<>();
9332            }
9333            mPostSystemReadyMessages.add(msg);
9334        }
9335    }
9336
9337    void startCleaningPackages() {
9338        // reader
9339        synchronized (mPackages) {
9340            if (!isExternalMediaAvailable()) {
9341                return;
9342            }
9343            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9344                return;
9345            }
9346        }
9347        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9348        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9349        IActivityManager am = ActivityManagerNative.getDefault();
9350        if (am != null) {
9351            try {
9352                am.startService(null, intent, null, mContext.getOpPackageName(),
9353                        UserHandle.USER_OWNER);
9354            } catch (RemoteException e) {
9355            }
9356        }
9357    }
9358
9359    @Override
9360    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9361            int installFlags, String installerPackageName, VerificationParams verificationParams,
9362            String packageAbiOverride) {
9363        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9364                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9365    }
9366
9367    @Override
9368    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9369            int installFlags, String installerPackageName, VerificationParams verificationParams,
9370            String packageAbiOverride, int userId) {
9371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9372
9373        final int callingUid = Binder.getCallingUid();
9374        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9375
9376        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9377            try {
9378                if (observer != null) {
9379                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9380                }
9381            } catch (RemoteException re) {
9382            }
9383            return;
9384        }
9385
9386        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9387            installFlags |= PackageManager.INSTALL_FROM_ADB;
9388
9389        } else {
9390            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9391            // about installerPackageName.
9392
9393            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9394            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9395        }
9396
9397        UserHandle user;
9398        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9399            user = UserHandle.ALL;
9400        } else {
9401            user = new UserHandle(userId);
9402        }
9403
9404        // Only system components can circumvent runtime permissions when installing.
9405        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9406                && mContext.checkCallingOrSelfPermission(Manifest.permission
9407                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9408            throw new SecurityException("You need the "
9409                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9410                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9411        }
9412
9413        verificationParams.setInstallerUid(callingUid);
9414
9415        final File originFile = new File(originPath);
9416        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9417
9418        final Message msg = mHandler.obtainMessage(INIT_COPY);
9419        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9420                null, verificationParams, user, packageAbiOverride);
9421        mHandler.sendMessage(msg);
9422    }
9423
9424    void installStage(String packageName, File stagedDir, String stagedCid,
9425            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9426            String installerPackageName, int installerUid, UserHandle user) {
9427        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9428                params.referrerUri, installerUid, null);
9429        verifParams.setInstallerUid(installerUid);
9430
9431        final OriginInfo origin;
9432        if (stagedDir != null) {
9433            origin = OriginInfo.fromStagedFile(stagedDir);
9434        } else {
9435            origin = OriginInfo.fromStagedContainer(stagedCid);
9436        }
9437
9438        final Message msg = mHandler.obtainMessage(INIT_COPY);
9439        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9440                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9441        mHandler.sendMessage(msg);
9442    }
9443
9444    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9445        Bundle extras = new Bundle(1);
9446        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9447
9448        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9449                packageName, extras, null, null, new int[] {userId});
9450        try {
9451            IActivityManager am = ActivityManagerNative.getDefault();
9452            final boolean isSystem =
9453                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9454            if (isSystem && am.isUserRunning(userId, false)) {
9455                // The just-installed/enabled app is bundled on the system, so presumed
9456                // to be able to run automatically without needing an explicit launch.
9457                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9458                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9459                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9460                        .setPackage(packageName);
9461                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9462                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9463            }
9464        } catch (RemoteException e) {
9465            // shouldn't happen
9466            Slog.w(TAG, "Unable to bootstrap installed package", e);
9467        }
9468    }
9469
9470    @Override
9471    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9472            int userId) {
9473        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9474        PackageSetting pkgSetting;
9475        final int uid = Binder.getCallingUid();
9476        enforceCrossUserPermission(uid, userId, true, true,
9477                "setApplicationHiddenSetting for user " + userId);
9478
9479        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9480            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9481            return false;
9482        }
9483
9484        long callingId = Binder.clearCallingIdentity();
9485        try {
9486            boolean sendAdded = false;
9487            boolean sendRemoved = false;
9488            // writer
9489            synchronized (mPackages) {
9490                pkgSetting = mSettings.mPackages.get(packageName);
9491                if (pkgSetting == null) {
9492                    return false;
9493                }
9494                if (pkgSetting.getHidden(userId) != hidden) {
9495                    pkgSetting.setHidden(hidden, userId);
9496                    mSettings.writePackageRestrictionsLPr(userId);
9497                    if (hidden) {
9498                        sendRemoved = true;
9499                    } else {
9500                        sendAdded = true;
9501                    }
9502                }
9503            }
9504            if (sendAdded) {
9505                sendPackageAddedForUser(packageName, pkgSetting, userId);
9506                return true;
9507            }
9508            if (sendRemoved) {
9509                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9510                        "hiding pkg");
9511                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9512            }
9513        } finally {
9514            Binder.restoreCallingIdentity(callingId);
9515        }
9516        return false;
9517    }
9518
9519    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9520            int userId) {
9521        final PackageRemovedInfo info = new PackageRemovedInfo();
9522        info.removedPackage = packageName;
9523        info.removedUsers = new int[] {userId};
9524        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9525        info.sendBroadcast(false, false, false);
9526    }
9527
9528    /**
9529     * Returns true if application is not found or there was an error. Otherwise it returns
9530     * the hidden state of the package for the given user.
9531     */
9532    @Override
9533    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9534        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9535        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9536                false, "getApplicationHidden for user " + userId);
9537        PackageSetting pkgSetting;
9538        long callingId = Binder.clearCallingIdentity();
9539        try {
9540            // writer
9541            synchronized (mPackages) {
9542                pkgSetting = mSettings.mPackages.get(packageName);
9543                if (pkgSetting == null) {
9544                    return true;
9545                }
9546                return pkgSetting.getHidden(userId);
9547            }
9548        } finally {
9549            Binder.restoreCallingIdentity(callingId);
9550        }
9551    }
9552
9553    /**
9554     * @hide
9555     */
9556    @Override
9557    public int installExistingPackageAsUser(String packageName, int userId) {
9558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9559                null);
9560        PackageSetting pkgSetting;
9561        final int uid = Binder.getCallingUid();
9562        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9563                + userId);
9564        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9565            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9566        }
9567
9568        long callingId = Binder.clearCallingIdentity();
9569        try {
9570            boolean sendAdded = false;
9571
9572            // writer
9573            synchronized (mPackages) {
9574                pkgSetting = mSettings.mPackages.get(packageName);
9575                if (pkgSetting == null) {
9576                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9577                }
9578                if (!pkgSetting.getInstalled(userId)) {
9579                    pkgSetting.setInstalled(true, userId);
9580                    pkgSetting.setHidden(false, userId);
9581                    mSettings.writePackageRestrictionsLPr(userId);
9582                    sendAdded = true;
9583                }
9584            }
9585
9586            if (sendAdded) {
9587                sendPackageAddedForUser(packageName, pkgSetting, userId);
9588            }
9589        } finally {
9590            Binder.restoreCallingIdentity(callingId);
9591        }
9592
9593        return PackageManager.INSTALL_SUCCEEDED;
9594    }
9595
9596    boolean isUserRestricted(int userId, String restrictionKey) {
9597        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9598        if (restrictions.getBoolean(restrictionKey, false)) {
9599            Log.w(TAG, "User is restricted: " + restrictionKey);
9600            return true;
9601        }
9602        return false;
9603    }
9604
9605    @Override
9606    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9607        mContext.enforceCallingOrSelfPermission(
9608                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9609                "Only package verification agents can verify applications");
9610
9611        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9612        final PackageVerificationResponse response = new PackageVerificationResponse(
9613                verificationCode, Binder.getCallingUid());
9614        msg.arg1 = id;
9615        msg.obj = response;
9616        mHandler.sendMessage(msg);
9617    }
9618
9619    @Override
9620    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9621            long millisecondsToDelay) {
9622        mContext.enforceCallingOrSelfPermission(
9623                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9624                "Only package verification agents can extend verification timeouts");
9625
9626        final PackageVerificationState state = mPendingVerification.get(id);
9627        final PackageVerificationResponse response = new PackageVerificationResponse(
9628                verificationCodeAtTimeout, Binder.getCallingUid());
9629
9630        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9631            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9632        }
9633        if (millisecondsToDelay < 0) {
9634            millisecondsToDelay = 0;
9635        }
9636        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9637                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9638            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9639        }
9640
9641        if ((state != null) && !state.timeoutExtended()) {
9642            state.extendTimeout();
9643
9644            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9645            msg.arg1 = id;
9646            msg.obj = response;
9647            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9648        }
9649    }
9650
9651    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9652            int verificationCode, UserHandle user) {
9653        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9654        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9655        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9656        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9657        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9658
9659        mContext.sendBroadcastAsUser(intent, user,
9660                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9661    }
9662
9663    private ComponentName matchComponentForVerifier(String packageName,
9664            List<ResolveInfo> receivers) {
9665        ActivityInfo targetReceiver = null;
9666
9667        final int NR = receivers.size();
9668        for (int i = 0; i < NR; i++) {
9669            final ResolveInfo info = receivers.get(i);
9670            if (info.activityInfo == null) {
9671                continue;
9672            }
9673
9674            if (packageName.equals(info.activityInfo.packageName)) {
9675                targetReceiver = info.activityInfo;
9676                break;
9677            }
9678        }
9679
9680        if (targetReceiver == null) {
9681            return null;
9682        }
9683
9684        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9685    }
9686
9687    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9688            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9689        if (pkgInfo.verifiers.length == 0) {
9690            return null;
9691        }
9692
9693        final int N = pkgInfo.verifiers.length;
9694        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9695        for (int i = 0; i < N; i++) {
9696            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9697
9698            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9699                    receivers);
9700            if (comp == null) {
9701                continue;
9702            }
9703
9704            final int verifierUid = getUidForVerifier(verifierInfo);
9705            if (verifierUid == -1) {
9706                continue;
9707            }
9708
9709            if (DEBUG_VERIFY) {
9710                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9711                        + " with the correct signature");
9712            }
9713            sufficientVerifiers.add(comp);
9714            verificationState.addSufficientVerifier(verifierUid);
9715        }
9716
9717        return sufficientVerifiers;
9718    }
9719
9720    private int getUidForVerifier(VerifierInfo verifierInfo) {
9721        synchronized (mPackages) {
9722            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9723            if (pkg == null) {
9724                return -1;
9725            } else if (pkg.mSignatures.length != 1) {
9726                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9727                        + " has more than one signature; ignoring");
9728                return -1;
9729            }
9730
9731            /*
9732             * If the public key of the package's signature does not match
9733             * our expected public key, then this is a different package and
9734             * we should skip.
9735             */
9736
9737            final byte[] expectedPublicKey;
9738            try {
9739                final Signature verifierSig = pkg.mSignatures[0];
9740                final PublicKey publicKey = verifierSig.getPublicKey();
9741                expectedPublicKey = publicKey.getEncoded();
9742            } catch (CertificateException e) {
9743                return -1;
9744            }
9745
9746            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9747
9748            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9749                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9750                        + " does not have the expected public key; ignoring");
9751                return -1;
9752            }
9753
9754            return pkg.applicationInfo.uid;
9755        }
9756    }
9757
9758    @Override
9759    public void finishPackageInstall(int token) {
9760        enforceSystemOrRoot("Only the system is allowed to finish installs");
9761
9762        if (DEBUG_INSTALL) {
9763            Slog.v(TAG, "BM finishing package install for " + token);
9764        }
9765
9766        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9767        mHandler.sendMessage(msg);
9768    }
9769
9770    /**
9771     * Get the verification agent timeout.
9772     *
9773     * @return verification timeout in milliseconds
9774     */
9775    private long getVerificationTimeout() {
9776        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9777                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9778                DEFAULT_VERIFICATION_TIMEOUT);
9779    }
9780
9781    /**
9782     * Get the default verification agent response code.
9783     *
9784     * @return default verification response code
9785     */
9786    private int getDefaultVerificationResponse() {
9787        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9788                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9789                DEFAULT_VERIFICATION_RESPONSE);
9790    }
9791
9792    /**
9793     * Check whether or not package verification has been enabled.
9794     *
9795     * @return true if verification should be performed
9796     */
9797    private boolean isVerificationEnabled(int userId, int installFlags) {
9798        if (!DEFAULT_VERIFY_ENABLE) {
9799            return false;
9800        }
9801
9802        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9803
9804        // Check if installing from ADB
9805        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9806            // Do not run verification in a test harness environment
9807            if (ActivityManager.isRunningInTestHarness()) {
9808                return false;
9809            }
9810            if (ensureVerifyAppsEnabled) {
9811                return true;
9812            }
9813            // Check if the developer does not want package verification for ADB installs
9814            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9815                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9816                return false;
9817            }
9818        }
9819
9820        if (ensureVerifyAppsEnabled) {
9821            return true;
9822        }
9823
9824        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9825                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9826    }
9827
9828    @Override
9829    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9830            throws RemoteException {
9831        mContext.enforceCallingOrSelfPermission(
9832                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9833                "Only intentfilter verification agents can verify applications");
9834
9835        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9836        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9837                Binder.getCallingUid(), verificationCode, failedDomains);
9838        msg.arg1 = id;
9839        msg.obj = response;
9840        mHandler.sendMessage(msg);
9841    }
9842
9843    @Override
9844    public int getIntentVerificationStatus(String packageName, int userId) {
9845        synchronized (mPackages) {
9846            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9847        }
9848    }
9849
9850    @Override
9851    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9852        mContext.enforceCallingOrSelfPermission(
9853                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9854
9855        boolean result = false;
9856        synchronized (mPackages) {
9857            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9858        }
9859        if (result) {
9860            scheduleWritePackageRestrictionsLocked(userId);
9861        }
9862        return result;
9863    }
9864
9865    @Override
9866    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9867        synchronized (mPackages) {
9868            return mSettings.getIntentFilterVerificationsLPr(packageName);
9869        }
9870    }
9871
9872    @Override
9873    public List<IntentFilter> getAllIntentFilters(String packageName) {
9874        if (TextUtils.isEmpty(packageName)) {
9875            return Collections.<IntentFilter>emptyList();
9876        }
9877        synchronized (mPackages) {
9878            PackageParser.Package pkg = mPackages.get(packageName);
9879            if (pkg == null || pkg.activities == null) {
9880                return Collections.<IntentFilter>emptyList();
9881            }
9882            final int count = pkg.activities.size();
9883            ArrayList<IntentFilter> result = new ArrayList<>();
9884            for (int n=0; n<count; n++) {
9885                PackageParser.Activity activity = pkg.activities.get(n);
9886                if (activity.intents != null || activity.intents.size() > 0) {
9887                    result.addAll(activity.intents);
9888                }
9889            }
9890            return result;
9891        }
9892    }
9893
9894    @Override
9895    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9896        mContext.enforceCallingOrSelfPermission(
9897                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9898
9899        synchronized (mPackages) {
9900            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9901            if (packageName != null) {
9902                result |= updateIntentVerificationStatus(packageName,
9903                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9904                        UserHandle.myUserId());
9905                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9906                        packageName, userId);
9907            }
9908            return result;
9909        }
9910    }
9911
9912    @Override
9913    public String getDefaultBrowserPackageName(int userId) {
9914        synchronized (mPackages) {
9915            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9916        }
9917    }
9918
9919    /**
9920     * Get the "allow unknown sources" setting.
9921     *
9922     * @return the current "allow unknown sources" setting
9923     */
9924    private int getUnknownSourcesSettings() {
9925        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9926                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9927                -1);
9928    }
9929
9930    @Override
9931    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9932        final int uid = Binder.getCallingUid();
9933        // writer
9934        synchronized (mPackages) {
9935            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9936            if (targetPackageSetting == null) {
9937                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9938            }
9939
9940            PackageSetting installerPackageSetting;
9941            if (installerPackageName != null) {
9942                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9943                if (installerPackageSetting == null) {
9944                    throw new IllegalArgumentException("Unknown installer package: "
9945                            + installerPackageName);
9946                }
9947            } else {
9948                installerPackageSetting = null;
9949            }
9950
9951            Signature[] callerSignature;
9952            Object obj = mSettings.getUserIdLPr(uid);
9953            if (obj != null) {
9954                if (obj instanceof SharedUserSetting) {
9955                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9956                } else if (obj instanceof PackageSetting) {
9957                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9958                } else {
9959                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9960                }
9961            } else {
9962                throw new SecurityException("Unknown calling uid " + uid);
9963            }
9964
9965            // Verify: can't set installerPackageName to a package that is
9966            // not signed with the same cert as the caller.
9967            if (installerPackageSetting != null) {
9968                if (compareSignatures(callerSignature,
9969                        installerPackageSetting.signatures.mSignatures)
9970                        != PackageManager.SIGNATURE_MATCH) {
9971                    throw new SecurityException(
9972                            "Caller does not have same cert as new installer package "
9973                            + installerPackageName);
9974                }
9975            }
9976
9977            // Verify: if target already has an installer package, it must
9978            // be signed with the same cert as the caller.
9979            if (targetPackageSetting.installerPackageName != null) {
9980                PackageSetting setting = mSettings.mPackages.get(
9981                        targetPackageSetting.installerPackageName);
9982                // If the currently set package isn't valid, then it's always
9983                // okay to change it.
9984                if (setting != null) {
9985                    if (compareSignatures(callerSignature,
9986                            setting.signatures.mSignatures)
9987                            != PackageManager.SIGNATURE_MATCH) {
9988                        throw new SecurityException(
9989                                "Caller does not have same cert as old installer package "
9990                                + targetPackageSetting.installerPackageName);
9991                    }
9992                }
9993            }
9994
9995            // Okay!
9996            targetPackageSetting.installerPackageName = installerPackageName;
9997            scheduleWriteSettingsLocked();
9998        }
9999    }
10000
10001    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10002        // Queue up an async operation since the package installation may take a little while.
10003        mHandler.post(new Runnable() {
10004            public void run() {
10005                mHandler.removeCallbacks(this);
10006                 // Result object to be returned
10007                PackageInstalledInfo res = new PackageInstalledInfo();
10008                res.returnCode = currentStatus;
10009                res.uid = -1;
10010                res.pkg = null;
10011                res.removedInfo = new PackageRemovedInfo();
10012                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10013                    args.doPreInstall(res.returnCode);
10014                    synchronized (mInstallLock) {
10015                        installPackageLI(args, res);
10016                    }
10017                    args.doPostInstall(res.returnCode, res.uid);
10018                }
10019
10020                // A restore should be performed at this point if (a) the install
10021                // succeeded, (b) the operation is not an update, and (c) the new
10022                // package has not opted out of backup participation.
10023                final boolean update = res.removedInfo.removedPackage != null;
10024                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10025                boolean doRestore = !update
10026                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10027
10028                // Set up the post-install work request bookkeeping.  This will be used
10029                // and cleaned up by the post-install event handling regardless of whether
10030                // there's a restore pass performed.  Token values are >= 1.
10031                int token;
10032                if (mNextInstallToken < 0) mNextInstallToken = 1;
10033                token = mNextInstallToken++;
10034
10035                PostInstallData data = new PostInstallData(args, res);
10036                mRunningInstalls.put(token, data);
10037                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10038
10039                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10040                    // Pass responsibility to the Backup Manager.  It will perform a
10041                    // restore if appropriate, then pass responsibility back to the
10042                    // Package Manager to run the post-install observer callbacks
10043                    // and broadcasts.
10044                    IBackupManager bm = IBackupManager.Stub.asInterface(
10045                            ServiceManager.getService(Context.BACKUP_SERVICE));
10046                    if (bm != null) {
10047                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10048                                + " to BM for possible restore");
10049                        try {
10050                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10051                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10052                            } else {
10053                                doRestore = false;
10054                            }
10055                        } catch (RemoteException e) {
10056                            // can't happen; the backup manager is local
10057                        } catch (Exception e) {
10058                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10059                            doRestore = false;
10060                        }
10061                    } else {
10062                        Slog.e(TAG, "Backup Manager not found!");
10063                        doRestore = false;
10064                    }
10065                }
10066
10067                if (!doRestore) {
10068                    // No restore possible, or the Backup Manager was mysteriously not
10069                    // available -- just fire the post-install work request directly.
10070                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10071                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10072                    mHandler.sendMessage(msg);
10073                }
10074            }
10075        });
10076    }
10077
10078    private abstract class HandlerParams {
10079        private static final int MAX_RETRIES = 4;
10080
10081        /**
10082         * Number of times startCopy() has been attempted and had a non-fatal
10083         * error.
10084         */
10085        private int mRetries = 0;
10086
10087        /** User handle for the user requesting the information or installation. */
10088        private final UserHandle mUser;
10089
10090        HandlerParams(UserHandle user) {
10091            mUser = user;
10092        }
10093
10094        UserHandle getUser() {
10095            return mUser;
10096        }
10097
10098        final boolean startCopy() {
10099            boolean res;
10100            try {
10101                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10102
10103                if (++mRetries > MAX_RETRIES) {
10104                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10105                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10106                    handleServiceError();
10107                    return false;
10108                } else {
10109                    handleStartCopy();
10110                    res = true;
10111                }
10112            } catch (RemoteException e) {
10113                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10114                mHandler.sendEmptyMessage(MCS_RECONNECT);
10115                res = false;
10116            }
10117            handleReturnCode();
10118            return res;
10119        }
10120
10121        final void serviceError() {
10122            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10123            handleServiceError();
10124            handleReturnCode();
10125        }
10126
10127        abstract void handleStartCopy() throws RemoteException;
10128        abstract void handleServiceError();
10129        abstract void handleReturnCode();
10130    }
10131
10132    class MeasureParams extends HandlerParams {
10133        private final PackageStats mStats;
10134        private boolean mSuccess;
10135
10136        private final IPackageStatsObserver mObserver;
10137
10138        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10139            super(new UserHandle(stats.userHandle));
10140            mObserver = observer;
10141            mStats = stats;
10142        }
10143
10144        @Override
10145        public String toString() {
10146            return "MeasureParams{"
10147                + Integer.toHexString(System.identityHashCode(this))
10148                + " " + mStats.packageName + "}";
10149        }
10150
10151        @Override
10152        void handleStartCopy() throws RemoteException {
10153            synchronized (mInstallLock) {
10154                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10155            }
10156
10157            if (mSuccess) {
10158                final boolean mounted;
10159                if (Environment.isExternalStorageEmulated()) {
10160                    mounted = true;
10161                } else {
10162                    final String status = Environment.getExternalStorageState();
10163                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10164                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10165                }
10166
10167                if (mounted) {
10168                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10169
10170                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10171                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10172
10173                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10174                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10175
10176                    // Always subtract cache size, since it's a subdirectory
10177                    mStats.externalDataSize -= mStats.externalCacheSize;
10178
10179                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10180                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10181
10182                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10183                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10184                }
10185            }
10186        }
10187
10188        @Override
10189        void handleReturnCode() {
10190            if (mObserver != null) {
10191                try {
10192                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10193                } catch (RemoteException e) {
10194                    Slog.i(TAG, "Observer no longer exists.");
10195                }
10196            }
10197        }
10198
10199        @Override
10200        void handleServiceError() {
10201            Slog.e(TAG, "Could not measure application " + mStats.packageName
10202                            + " external storage");
10203        }
10204    }
10205
10206    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10207            throws RemoteException {
10208        long result = 0;
10209        for (File path : paths) {
10210            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10211        }
10212        return result;
10213    }
10214
10215    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10216        for (File path : paths) {
10217            try {
10218                mcs.clearDirectory(path.getAbsolutePath());
10219            } catch (RemoteException e) {
10220            }
10221        }
10222    }
10223
10224    static class OriginInfo {
10225        /**
10226         * Location where install is coming from, before it has been
10227         * copied/renamed into place. This could be a single monolithic APK
10228         * file, or a cluster directory. This location may be untrusted.
10229         */
10230        final File file;
10231        final String cid;
10232
10233        /**
10234         * Flag indicating that {@link #file} or {@link #cid} has already been
10235         * staged, meaning downstream users don't need to defensively copy the
10236         * contents.
10237         */
10238        final boolean staged;
10239
10240        /**
10241         * Flag indicating that {@link #file} or {@link #cid} is an already
10242         * installed app that is being moved.
10243         */
10244        final boolean existing;
10245
10246        final String resolvedPath;
10247        final File resolvedFile;
10248
10249        static OriginInfo fromNothing() {
10250            return new OriginInfo(null, null, false, false);
10251        }
10252
10253        static OriginInfo fromUntrustedFile(File file) {
10254            return new OriginInfo(file, null, false, false);
10255        }
10256
10257        static OriginInfo fromExistingFile(File file) {
10258            return new OriginInfo(file, null, false, true);
10259        }
10260
10261        static OriginInfo fromStagedFile(File file) {
10262            return new OriginInfo(file, null, true, false);
10263        }
10264
10265        static OriginInfo fromStagedContainer(String cid) {
10266            return new OriginInfo(null, cid, true, false);
10267        }
10268
10269        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10270            this.file = file;
10271            this.cid = cid;
10272            this.staged = staged;
10273            this.existing = existing;
10274
10275            if (cid != null) {
10276                resolvedPath = PackageHelper.getSdDir(cid);
10277                resolvedFile = new File(resolvedPath);
10278            } else if (file != null) {
10279                resolvedPath = file.getAbsolutePath();
10280                resolvedFile = file;
10281            } else {
10282                resolvedPath = null;
10283                resolvedFile = null;
10284            }
10285        }
10286    }
10287
10288    class MoveInfo {
10289        final int moveId;
10290        final String fromUuid;
10291        final String toUuid;
10292        final String packageName;
10293        final String dataAppName;
10294        final int appId;
10295        final String seinfo;
10296
10297        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10298                String dataAppName, int appId, String seinfo) {
10299            this.moveId = moveId;
10300            this.fromUuid = fromUuid;
10301            this.toUuid = toUuid;
10302            this.packageName = packageName;
10303            this.dataAppName = dataAppName;
10304            this.appId = appId;
10305            this.seinfo = seinfo;
10306        }
10307    }
10308
10309    class InstallParams extends HandlerParams {
10310        final OriginInfo origin;
10311        final MoveInfo move;
10312        final IPackageInstallObserver2 observer;
10313        int installFlags;
10314        final String installerPackageName;
10315        final String volumeUuid;
10316        final VerificationParams verificationParams;
10317        private InstallArgs mArgs;
10318        private int mRet;
10319        final String packageAbiOverride;
10320
10321        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10322                int installFlags, String installerPackageName, String volumeUuid,
10323                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10324            super(user);
10325            this.origin = origin;
10326            this.move = move;
10327            this.observer = observer;
10328            this.installFlags = installFlags;
10329            this.installerPackageName = installerPackageName;
10330            this.volumeUuid = volumeUuid;
10331            this.verificationParams = verificationParams;
10332            this.packageAbiOverride = packageAbiOverride;
10333        }
10334
10335        @Override
10336        public String toString() {
10337            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10338                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10339        }
10340
10341        public ManifestDigest getManifestDigest() {
10342            if (verificationParams == null) {
10343                return null;
10344            }
10345            return verificationParams.getManifestDigest();
10346        }
10347
10348        private int installLocationPolicy(PackageInfoLite pkgLite) {
10349            String packageName = pkgLite.packageName;
10350            int installLocation = pkgLite.installLocation;
10351            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10352            // reader
10353            synchronized (mPackages) {
10354                PackageParser.Package pkg = mPackages.get(packageName);
10355                if (pkg != null) {
10356                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10357                        // Check for downgrading.
10358                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10359                            try {
10360                                checkDowngrade(pkg, pkgLite);
10361                            } catch (PackageManagerException e) {
10362                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10363                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10364                            }
10365                        }
10366                        // Check for updated system application.
10367                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10368                            if (onSd) {
10369                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10370                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10371                            }
10372                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10373                        } else {
10374                            if (onSd) {
10375                                // Install flag overrides everything.
10376                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10377                            }
10378                            // If current upgrade specifies particular preference
10379                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10380                                // Application explicitly specified internal.
10381                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10382                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10383                                // App explictly prefers external. Let policy decide
10384                            } else {
10385                                // Prefer previous location
10386                                if (isExternal(pkg)) {
10387                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10388                                }
10389                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10390                            }
10391                        }
10392                    } else {
10393                        // Invalid install. Return error code
10394                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10395                    }
10396                }
10397            }
10398            // All the special cases have been taken care of.
10399            // Return result based on recommended install location.
10400            if (onSd) {
10401                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10402            }
10403            return pkgLite.recommendedInstallLocation;
10404        }
10405
10406        /*
10407         * Invoke remote method to get package information and install
10408         * location values. Override install location based on default
10409         * policy if needed and then create install arguments based
10410         * on the install location.
10411         */
10412        public void handleStartCopy() throws RemoteException {
10413            int ret = PackageManager.INSTALL_SUCCEEDED;
10414
10415            // If we're already staged, we've firmly committed to an install location
10416            if (origin.staged) {
10417                if (origin.file != null) {
10418                    installFlags |= PackageManager.INSTALL_INTERNAL;
10419                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10420                } else if (origin.cid != null) {
10421                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10422                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10423                } else {
10424                    throw new IllegalStateException("Invalid stage location");
10425                }
10426            }
10427
10428            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10429            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10430
10431            PackageInfoLite pkgLite = null;
10432
10433            if (onInt && onSd) {
10434                // Check if both bits are set.
10435                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10436                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10437            } else {
10438                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10439                        packageAbiOverride);
10440
10441                /*
10442                 * If we have too little free space, try to free cache
10443                 * before giving up.
10444                 */
10445                if (!origin.staged && pkgLite.recommendedInstallLocation
10446                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10447                    // TODO: focus freeing disk space on the target device
10448                    final StorageManager storage = StorageManager.from(mContext);
10449                    final long lowThreshold = storage.getStorageLowBytes(
10450                            Environment.getDataDirectory());
10451
10452                    final long sizeBytes = mContainerService.calculateInstalledSize(
10453                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10454
10455                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10456                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10457                                installFlags, packageAbiOverride);
10458                    }
10459
10460                    /*
10461                     * The cache free must have deleted the file we
10462                     * downloaded to install.
10463                     *
10464                     * TODO: fix the "freeCache" call to not delete
10465                     *       the file we care about.
10466                     */
10467                    if (pkgLite.recommendedInstallLocation
10468                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10469                        pkgLite.recommendedInstallLocation
10470                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10471                    }
10472                }
10473            }
10474
10475            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10476                int loc = pkgLite.recommendedInstallLocation;
10477                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10478                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10479                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10480                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10481                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10482                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10483                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10484                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10485                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10486                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10487                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10488                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10489                } else {
10490                    // Override with defaults if needed.
10491                    loc = installLocationPolicy(pkgLite);
10492                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10493                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10494                    } else if (!onSd && !onInt) {
10495                        // Override install location with flags
10496                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10497                            // Set the flag to install on external media.
10498                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10499                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10500                        } else {
10501                            // Make sure the flag for installing on external
10502                            // media is unset
10503                            installFlags |= PackageManager.INSTALL_INTERNAL;
10504                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10505                        }
10506                    }
10507                }
10508            }
10509
10510            final InstallArgs args = createInstallArgs(this);
10511            mArgs = args;
10512
10513            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10514                 /*
10515                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10516                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10517                 */
10518                int userIdentifier = getUser().getIdentifier();
10519                if (userIdentifier == UserHandle.USER_ALL
10520                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10521                    userIdentifier = UserHandle.USER_OWNER;
10522                }
10523
10524                /*
10525                 * Determine if we have any installed package verifiers. If we
10526                 * do, then we'll defer to them to verify the packages.
10527                 */
10528                final int requiredUid = mRequiredVerifierPackage == null ? -1
10529                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10530                if (!origin.existing && requiredUid != -1
10531                        && isVerificationEnabled(userIdentifier, installFlags)) {
10532                    final Intent verification = new Intent(
10533                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10534                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10535                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10536                            PACKAGE_MIME_TYPE);
10537                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10538
10539                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10540                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10541                            0 /* TODO: Which userId? */);
10542
10543                    if (DEBUG_VERIFY) {
10544                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10545                                + verification.toString() + " with " + pkgLite.verifiers.length
10546                                + " optional verifiers");
10547                    }
10548
10549                    final int verificationId = mPendingVerificationToken++;
10550
10551                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10552
10553                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10554                            installerPackageName);
10555
10556                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10557                            installFlags);
10558
10559                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10560                            pkgLite.packageName);
10561
10562                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10563                            pkgLite.versionCode);
10564
10565                    if (verificationParams != null) {
10566                        if (verificationParams.getVerificationURI() != null) {
10567                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10568                                 verificationParams.getVerificationURI());
10569                        }
10570                        if (verificationParams.getOriginatingURI() != null) {
10571                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10572                                  verificationParams.getOriginatingURI());
10573                        }
10574                        if (verificationParams.getReferrer() != null) {
10575                            verification.putExtra(Intent.EXTRA_REFERRER,
10576                                  verificationParams.getReferrer());
10577                        }
10578                        if (verificationParams.getOriginatingUid() >= 0) {
10579                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10580                                  verificationParams.getOriginatingUid());
10581                        }
10582                        if (verificationParams.getInstallerUid() >= 0) {
10583                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10584                                  verificationParams.getInstallerUid());
10585                        }
10586                    }
10587
10588                    final PackageVerificationState verificationState = new PackageVerificationState(
10589                            requiredUid, args);
10590
10591                    mPendingVerification.append(verificationId, verificationState);
10592
10593                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10594                            receivers, verificationState);
10595
10596                    /*
10597                     * If any sufficient verifiers were listed in the package
10598                     * manifest, attempt to ask them.
10599                     */
10600                    if (sufficientVerifiers != null) {
10601                        final int N = sufficientVerifiers.size();
10602                        if (N == 0) {
10603                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10604                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10605                        } else {
10606                            for (int i = 0; i < N; i++) {
10607                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10608
10609                                final Intent sufficientIntent = new Intent(verification);
10610                                sufficientIntent.setComponent(verifierComponent);
10611
10612                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10613                            }
10614                        }
10615                    }
10616
10617                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10618                            mRequiredVerifierPackage, receivers);
10619                    if (ret == PackageManager.INSTALL_SUCCEEDED
10620                            && mRequiredVerifierPackage != null) {
10621                        /*
10622                         * Send the intent to the required verification agent,
10623                         * but only start the verification timeout after the
10624                         * target BroadcastReceivers have run.
10625                         */
10626                        verification.setComponent(requiredVerifierComponent);
10627                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10628                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10629                                new BroadcastReceiver() {
10630                                    @Override
10631                                    public void onReceive(Context context, Intent intent) {
10632                                        final Message msg = mHandler
10633                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10634                                        msg.arg1 = verificationId;
10635                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10636                                    }
10637                                }, null, 0, null, null);
10638
10639                        /*
10640                         * We don't want the copy to proceed until verification
10641                         * succeeds, so null out this field.
10642                         */
10643                        mArgs = null;
10644                    }
10645                } else {
10646                    /*
10647                     * No package verification is enabled, so immediately start
10648                     * the remote call to initiate copy using temporary file.
10649                     */
10650                    ret = args.copyApk(mContainerService, true);
10651                }
10652            }
10653
10654            mRet = ret;
10655        }
10656
10657        @Override
10658        void handleReturnCode() {
10659            // If mArgs is null, then MCS couldn't be reached. When it
10660            // reconnects, it will try again to install. At that point, this
10661            // will succeed.
10662            if (mArgs != null) {
10663                processPendingInstall(mArgs, mRet);
10664            }
10665        }
10666
10667        @Override
10668        void handleServiceError() {
10669            mArgs = createInstallArgs(this);
10670            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10671        }
10672
10673        public boolean isForwardLocked() {
10674            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10675        }
10676    }
10677
10678    /**
10679     * Used during creation of InstallArgs
10680     *
10681     * @param installFlags package installation flags
10682     * @return true if should be installed on external storage
10683     */
10684    private static boolean installOnExternalAsec(int installFlags) {
10685        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10686            return false;
10687        }
10688        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10689            return true;
10690        }
10691        return false;
10692    }
10693
10694    /**
10695     * Used during creation of InstallArgs
10696     *
10697     * @param installFlags package installation flags
10698     * @return true if should be installed as forward locked
10699     */
10700    private static boolean installForwardLocked(int installFlags) {
10701        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10702    }
10703
10704    private InstallArgs createInstallArgs(InstallParams params) {
10705        if (params.move != null) {
10706            return new MoveInstallArgs(params);
10707        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10708            return new AsecInstallArgs(params);
10709        } else {
10710            return new FileInstallArgs(params);
10711        }
10712    }
10713
10714    /**
10715     * Create args that describe an existing installed package. Typically used
10716     * when cleaning up old installs, or used as a move source.
10717     */
10718    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10719            String resourcePath, String[] instructionSets) {
10720        final boolean isInAsec;
10721        if (installOnExternalAsec(installFlags)) {
10722            /* Apps on SD card are always in ASEC containers. */
10723            isInAsec = true;
10724        } else if (installForwardLocked(installFlags)
10725                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10726            /*
10727             * Forward-locked apps are only in ASEC containers if they're the
10728             * new style
10729             */
10730            isInAsec = true;
10731        } else {
10732            isInAsec = false;
10733        }
10734
10735        if (isInAsec) {
10736            return new AsecInstallArgs(codePath, instructionSets,
10737                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10738        } else {
10739            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10740        }
10741    }
10742
10743    static abstract class InstallArgs {
10744        /** @see InstallParams#origin */
10745        final OriginInfo origin;
10746        /** @see InstallParams#move */
10747        final MoveInfo move;
10748
10749        final IPackageInstallObserver2 observer;
10750        // Always refers to PackageManager flags only
10751        final int installFlags;
10752        final String installerPackageName;
10753        final String volumeUuid;
10754        final ManifestDigest manifestDigest;
10755        final UserHandle user;
10756        final String abiOverride;
10757
10758        // The list of instruction sets supported by this app. This is currently
10759        // only used during the rmdex() phase to clean up resources. We can get rid of this
10760        // if we move dex files under the common app path.
10761        /* nullable */ String[] instructionSets;
10762
10763        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10764                int installFlags, String installerPackageName, String volumeUuid,
10765                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10766                String abiOverride) {
10767            this.origin = origin;
10768            this.move = move;
10769            this.installFlags = installFlags;
10770            this.observer = observer;
10771            this.installerPackageName = installerPackageName;
10772            this.volumeUuid = volumeUuid;
10773            this.manifestDigest = manifestDigest;
10774            this.user = user;
10775            this.instructionSets = instructionSets;
10776            this.abiOverride = abiOverride;
10777        }
10778
10779        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10780        abstract int doPreInstall(int status);
10781
10782        /**
10783         * Rename package into final resting place. All paths on the given
10784         * scanned package should be updated to reflect the rename.
10785         */
10786        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10787        abstract int doPostInstall(int status, int uid);
10788
10789        /** @see PackageSettingBase#codePathString */
10790        abstract String getCodePath();
10791        /** @see PackageSettingBase#resourcePathString */
10792        abstract String getResourcePath();
10793
10794        // Need installer lock especially for dex file removal.
10795        abstract void cleanUpResourcesLI();
10796        abstract boolean doPostDeleteLI(boolean delete);
10797
10798        /**
10799         * Called before the source arguments are copied. This is used mostly
10800         * for MoveParams when it needs to read the source file to put it in the
10801         * destination.
10802         */
10803        int doPreCopy() {
10804            return PackageManager.INSTALL_SUCCEEDED;
10805        }
10806
10807        /**
10808         * Called after the source arguments are copied. This is used mostly for
10809         * MoveParams when it needs to read the source file to put it in the
10810         * destination.
10811         *
10812         * @return
10813         */
10814        int doPostCopy(int uid) {
10815            return PackageManager.INSTALL_SUCCEEDED;
10816        }
10817
10818        protected boolean isFwdLocked() {
10819            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10820        }
10821
10822        protected boolean isExternalAsec() {
10823            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10824        }
10825
10826        UserHandle getUser() {
10827            return user;
10828        }
10829    }
10830
10831    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10832        if (!allCodePaths.isEmpty()) {
10833            if (instructionSets == null) {
10834                throw new IllegalStateException("instructionSet == null");
10835            }
10836            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10837            for (String codePath : allCodePaths) {
10838                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10839                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10840                    if (retCode < 0) {
10841                        Slog.w(TAG, "Couldn't remove dex file for package: "
10842                                + " at location " + codePath + ", retcode=" + retCode);
10843                        // we don't consider this to be a failure of the core package deletion
10844                    }
10845                }
10846            }
10847        }
10848    }
10849
10850    /**
10851     * Logic to handle installation of non-ASEC applications, including copying
10852     * and renaming logic.
10853     */
10854    class FileInstallArgs extends InstallArgs {
10855        private File codeFile;
10856        private File resourceFile;
10857
10858        // Example topology:
10859        // /data/app/com.example/base.apk
10860        // /data/app/com.example/split_foo.apk
10861        // /data/app/com.example/lib/arm/libfoo.so
10862        // /data/app/com.example/lib/arm64/libfoo.so
10863        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10864
10865        /** New install */
10866        FileInstallArgs(InstallParams params) {
10867            super(params.origin, params.move, params.observer, params.installFlags,
10868                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10869                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10870            if (isFwdLocked()) {
10871                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10872            }
10873        }
10874
10875        /** Existing install */
10876        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10877            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10878                    null);
10879            this.codeFile = (codePath != null) ? new File(codePath) : null;
10880            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10881        }
10882
10883        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10884            if (origin.staged) {
10885                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10886                codeFile = origin.file;
10887                resourceFile = origin.file;
10888                return PackageManager.INSTALL_SUCCEEDED;
10889            }
10890
10891            try {
10892                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10893                codeFile = tempDir;
10894                resourceFile = tempDir;
10895            } catch (IOException e) {
10896                Slog.w(TAG, "Failed to create copy file: " + e);
10897                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10898            }
10899
10900            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10901                @Override
10902                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10903                    if (!FileUtils.isValidExtFilename(name)) {
10904                        throw new IllegalArgumentException("Invalid filename: " + name);
10905                    }
10906                    try {
10907                        final File file = new File(codeFile, name);
10908                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10909                                O_RDWR | O_CREAT, 0644);
10910                        Os.chmod(file.getAbsolutePath(), 0644);
10911                        return new ParcelFileDescriptor(fd);
10912                    } catch (ErrnoException e) {
10913                        throw new RemoteException("Failed to open: " + e.getMessage());
10914                    }
10915                }
10916            };
10917
10918            int ret = PackageManager.INSTALL_SUCCEEDED;
10919            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10920            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10921                Slog.e(TAG, "Failed to copy package");
10922                return ret;
10923            }
10924
10925            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10926            NativeLibraryHelper.Handle handle = null;
10927            try {
10928                handle = NativeLibraryHelper.Handle.create(codeFile);
10929                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10930                        abiOverride);
10931            } catch (IOException e) {
10932                Slog.e(TAG, "Copying native libraries failed", e);
10933                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10934            } finally {
10935                IoUtils.closeQuietly(handle);
10936            }
10937
10938            return ret;
10939        }
10940
10941        int doPreInstall(int status) {
10942            if (status != PackageManager.INSTALL_SUCCEEDED) {
10943                cleanUp();
10944            }
10945            return status;
10946        }
10947
10948        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10949            if (status != PackageManager.INSTALL_SUCCEEDED) {
10950                cleanUp();
10951                return false;
10952            }
10953
10954            final File targetDir = codeFile.getParentFile();
10955            final File beforeCodeFile = codeFile;
10956            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10957
10958            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10959            try {
10960                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10961            } catch (ErrnoException e) {
10962                Slog.w(TAG, "Failed to rename", e);
10963                return false;
10964            }
10965
10966            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10967                Slog.w(TAG, "Failed to restorecon");
10968                return false;
10969            }
10970
10971            // Reflect the rename internally
10972            codeFile = afterCodeFile;
10973            resourceFile = afterCodeFile;
10974
10975            // Reflect the rename in scanned details
10976            pkg.codePath = afterCodeFile.getAbsolutePath();
10977            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10978                    pkg.baseCodePath);
10979            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10980                    pkg.splitCodePaths);
10981
10982            // Reflect the rename in app info
10983            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10984            pkg.applicationInfo.setCodePath(pkg.codePath);
10985            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10986            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10987            pkg.applicationInfo.setResourcePath(pkg.codePath);
10988            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10989            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10990
10991            return true;
10992        }
10993
10994        int doPostInstall(int status, int uid) {
10995            if (status != PackageManager.INSTALL_SUCCEEDED) {
10996                cleanUp();
10997            }
10998            return status;
10999        }
11000
11001        @Override
11002        String getCodePath() {
11003            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11004        }
11005
11006        @Override
11007        String getResourcePath() {
11008            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11009        }
11010
11011        private boolean cleanUp() {
11012            if (codeFile == null || !codeFile.exists()) {
11013                return false;
11014            }
11015
11016            if (codeFile.isDirectory()) {
11017                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11018            } else {
11019                codeFile.delete();
11020            }
11021
11022            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11023                resourceFile.delete();
11024            }
11025
11026            return true;
11027        }
11028
11029        void cleanUpResourcesLI() {
11030            // Try enumerating all code paths before deleting
11031            List<String> allCodePaths = Collections.EMPTY_LIST;
11032            if (codeFile != null && codeFile.exists()) {
11033                try {
11034                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11035                    allCodePaths = pkg.getAllCodePaths();
11036                } catch (PackageParserException e) {
11037                    // Ignored; we tried our best
11038                }
11039            }
11040
11041            cleanUp();
11042            removeDexFiles(allCodePaths, instructionSets);
11043        }
11044
11045        boolean doPostDeleteLI(boolean delete) {
11046            // XXX err, shouldn't we respect the delete flag?
11047            cleanUpResourcesLI();
11048            return true;
11049        }
11050    }
11051
11052    private boolean isAsecExternal(String cid) {
11053        final String asecPath = PackageHelper.getSdFilesystem(cid);
11054        return !asecPath.startsWith(mAsecInternalPath);
11055    }
11056
11057    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11058            PackageManagerException {
11059        if (copyRet < 0) {
11060            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11061                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11062                throw new PackageManagerException(copyRet, message);
11063            }
11064        }
11065    }
11066
11067    /**
11068     * Extract the MountService "container ID" from the full code path of an
11069     * .apk.
11070     */
11071    static String cidFromCodePath(String fullCodePath) {
11072        int eidx = fullCodePath.lastIndexOf("/");
11073        String subStr1 = fullCodePath.substring(0, eidx);
11074        int sidx = subStr1.lastIndexOf("/");
11075        return subStr1.substring(sidx+1, eidx);
11076    }
11077
11078    /**
11079     * Logic to handle installation of ASEC applications, including copying and
11080     * renaming logic.
11081     */
11082    class AsecInstallArgs extends InstallArgs {
11083        static final String RES_FILE_NAME = "pkg.apk";
11084        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11085
11086        String cid;
11087        String packagePath;
11088        String resourcePath;
11089
11090        /** New install */
11091        AsecInstallArgs(InstallParams params) {
11092            super(params.origin, params.move, params.observer, params.installFlags,
11093                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11094                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11095        }
11096
11097        /** Existing install */
11098        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11099                        boolean isExternal, boolean isForwardLocked) {
11100            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11101                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11102                    instructionSets, null);
11103            // Hackily pretend we're still looking at a full code path
11104            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11105                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11106            }
11107
11108            // Extract cid from fullCodePath
11109            int eidx = fullCodePath.lastIndexOf("/");
11110            String subStr1 = fullCodePath.substring(0, eidx);
11111            int sidx = subStr1.lastIndexOf("/");
11112            cid = subStr1.substring(sidx+1, eidx);
11113            setMountPath(subStr1);
11114        }
11115
11116        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11117            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11118                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11119                    instructionSets, null);
11120            this.cid = cid;
11121            setMountPath(PackageHelper.getSdDir(cid));
11122        }
11123
11124        void createCopyFile() {
11125            cid = mInstallerService.allocateExternalStageCidLegacy();
11126        }
11127
11128        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11129            if (origin.staged) {
11130                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11131                cid = origin.cid;
11132                setMountPath(PackageHelper.getSdDir(cid));
11133                return PackageManager.INSTALL_SUCCEEDED;
11134            }
11135
11136            if (temp) {
11137                createCopyFile();
11138            } else {
11139                /*
11140                 * Pre-emptively destroy the container since it's destroyed if
11141                 * copying fails due to it existing anyway.
11142                 */
11143                PackageHelper.destroySdDir(cid);
11144            }
11145
11146            final String newMountPath = imcs.copyPackageToContainer(
11147                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11148                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11149
11150            if (newMountPath != null) {
11151                setMountPath(newMountPath);
11152                return PackageManager.INSTALL_SUCCEEDED;
11153            } else {
11154                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11155            }
11156        }
11157
11158        @Override
11159        String getCodePath() {
11160            return packagePath;
11161        }
11162
11163        @Override
11164        String getResourcePath() {
11165            return resourcePath;
11166        }
11167
11168        int doPreInstall(int status) {
11169            if (status != PackageManager.INSTALL_SUCCEEDED) {
11170                // Destroy container
11171                PackageHelper.destroySdDir(cid);
11172            } else {
11173                boolean mounted = PackageHelper.isContainerMounted(cid);
11174                if (!mounted) {
11175                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11176                            Process.SYSTEM_UID);
11177                    if (newMountPath != null) {
11178                        setMountPath(newMountPath);
11179                    } else {
11180                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11181                    }
11182                }
11183            }
11184            return status;
11185        }
11186
11187        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11188            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11189            String newMountPath = null;
11190            if (PackageHelper.isContainerMounted(cid)) {
11191                // Unmount the container
11192                if (!PackageHelper.unMountSdDir(cid)) {
11193                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11194                    return false;
11195                }
11196            }
11197            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11198                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11199                        " which might be stale. Will try to clean up.");
11200                // Clean up the stale container and proceed to recreate.
11201                if (!PackageHelper.destroySdDir(newCacheId)) {
11202                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11203                    return false;
11204                }
11205                // Successfully cleaned up stale container. Try to rename again.
11206                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11207                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11208                            + " inspite of cleaning it up.");
11209                    return false;
11210                }
11211            }
11212            if (!PackageHelper.isContainerMounted(newCacheId)) {
11213                Slog.w(TAG, "Mounting container " + newCacheId);
11214                newMountPath = PackageHelper.mountSdDir(newCacheId,
11215                        getEncryptKey(), Process.SYSTEM_UID);
11216            } else {
11217                newMountPath = PackageHelper.getSdDir(newCacheId);
11218            }
11219            if (newMountPath == null) {
11220                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11221                return false;
11222            }
11223            Log.i(TAG, "Succesfully renamed " + cid +
11224                    " to " + newCacheId +
11225                    " at new path: " + newMountPath);
11226            cid = newCacheId;
11227
11228            final File beforeCodeFile = new File(packagePath);
11229            setMountPath(newMountPath);
11230            final File afterCodeFile = new File(packagePath);
11231
11232            // Reflect the rename in scanned details
11233            pkg.codePath = afterCodeFile.getAbsolutePath();
11234            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11235                    pkg.baseCodePath);
11236            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11237                    pkg.splitCodePaths);
11238
11239            // Reflect the rename in app info
11240            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11241            pkg.applicationInfo.setCodePath(pkg.codePath);
11242            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11243            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11244            pkg.applicationInfo.setResourcePath(pkg.codePath);
11245            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11246            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11247
11248            return true;
11249        }
11250
11251        private void setMountPath(String mountPath) {
11252            final File mountFile = new File(mountPath);
11253
11254            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11255            if (monolithicFile.exists()) {
11256                packagePath = monolithicFile.getAbsolutePath();
11257                if (isFwdLocked()) {
11258                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11259                } else {
11260                    resourcePath = packagePath;
11261                }
11262            } else {
11263                packagePath = mountFile.getAbsolutePath();
11264                resourcePath = packagePath;
11265            }
11266        }
11267
11268        int doPostInstall(int status, int uid) {
11269            if (status != PackageManager.INSTALL_SUCCEEDED) {
11270                cleanUp();
11271            } else {
11272                final int groupOwner;
11273                final String protectedFile;
11274                if (isFwdLocked()) {
11275                    groupOwner = UserHandle.getSharedAppGid(uid);
11276                    protectedFile = RES_FILE_NAME;
11277                } else {
11278                    groupOwner = -1;
11279                    protectedFile = null;
11280                }
11281
11282                if (uid < Process.FIRST_APPLICATION_UID
11283                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11284                    Slog.e(TAG, "Failed to finalize " + cid);
11285                    PackageHelper.destroySdDir(cid);
11286                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11287                }
11288
11289                boolean mounted = PackageHelper.isContainerMounted(cid);
11290                if (!mounted) {
11291                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11292                }
11293            }
11294            return status;
11295        }
11296
11297        private void cleanUp() {
11298            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11299
11300            // Destroy secure container
11301            PackageHelper.destroySdDir(cid);
11302        }
11303
11304        private List<String> getAllCodePaths() {
11305            final File codeFile = new File(getCodePath());
11306            if (codeFile != null && codeFile.exists()) {
11307                try {
11308                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11309                    return pkg.getAllCodePaths();
11310                } catch (PackageParserException e) {
11311                    // Ignored; we tried our best
11312                }
11313            }
11314            return Collections.EMPTY_LIST;
11315        }
11316
11317        void cleanUpResourcesLI() {
11318            // Enumerate all code paths before deleting
11319            cleanUpResourcesLI(getAllCodePaths());
11320        }
11321
11322        private void cleanUpResourcesLI(List<String> allCodePaths) {
11323            cleanUp();
11324            removeDexFiles(allCodePaths, instructionSets);
11325        }
11326
11327        String getPackageName() {
11328            return getAsecPackageName(cid);
11329        }
11330
11331        boolean doPostDeleteLI(boolean delete) {
11332            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11333            final List<String> allCodePaths = getAllCodePaths();
11334            boolean mounted = PackageHelper.isContainerMounted(cid);
11335            if (mounted) {
11336                // Unmount first
11337                if (PackageHelper.unMountSdDir(cid)) {
11338                    mounted = false;
11339                }
11340            }
11341            if (!mounted && delete) {
11342                cleanUpResourcesLI(allCodePaths);
11343            }
11344            return !mounted;
11345        }
11346
11347        @Override
11348        int doPreCopy() {
11349            if (isFwdLocked()) {
11350                if (!PackageHelper.fixSdPermissions(cid,
11351                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11352                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11353                }
11354            }
11355
11356            return PackageManager.INSTALL_SUCCEEDED;
11357        }
11358
11359        @Override
11360        int doPostCopy(int uid) {
11361            if (isFwdLocked()) {
11362                if (uid < Process.FIRST_APPLICATION_UID
11363                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11364                                RES_FILE_NAME)) {
11365                    Slog.e(TAG, "Failed to finalize " + cid);
11366                    PackageHelper.destroySdDir(cid);
11367                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11368                }
11369            }
11370
11371            return PackageManager.INSTALL_SUCCEEDED;
11372        }
11373    }
11374
11375    /**
11376     * Logic to handle movement of existing installed applications.
11377     */
11378    class MoveInstallArgs extends InstallArgs {
11379        private File codeFile;
11380        private File resourceFile;
11381
11382        /** New install */
11383        MoveInstallArgs(InstallParams params) {
11384            super(params.origin, params.move, params.observer, params.installFlags,
11385                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11386                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11387        }
11388
11389        int copyApk(IMediaContainerService imcs, boolean temp) {
11390            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11391                    + move.fromUuid + " to " + move.toUuid);
11392            synchronized (mInstaller) {
11393                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11394                        move.dataAppName, move.appId, move.seinfo) != 0) {
11395                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11396                }
11397            }
11398
11399            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11400            resourceFile = codeFile;
11401            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11402
11403            return PackageManager.INSTALL_SUCCEEDED;
11404        }
11405
11406        int doPreInstall(int status) {
11407            if (status != PackageManager.INSTALL_SUCCEEDED) {
11408                cleanUp(move.toUuid);
11409            }
11410            return status;
11411        }
11412
11413        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11414            if (status != PackageManager.INSTALL_SUCCEEDED) {
11415                cleanUp(move.toUuid);
11416                return false;
11417            }
11418
11419            // Reflect the move in app info
11420            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11421            pkg.applicationInfo.setCodePath(pkg.codePath);
11422            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11423            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11424            pkg.applicationInfo.setResourcePath(pkg.codePath);
11425            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11426            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11427
11428            return true;
11429        }
11430
11431        int doPostInstall(int status, int uid) {
11432            if (status == PackageManager.INSTALL_SUCCEEDED) {
11433                cleanUp(move.fromUuid);
11434            } else {
11435                cleanUp(move.toUuid);
11436            }
11437            return status;
11438        }
11439
11440        @Override
11441        String getCodePath() {
11442            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11443        }
11444
11445        @Override
11446        String getResourcePath() {
11447            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11448        }
11449
11450        private boolean cleanUp(String volumeUuid) {
11451            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11452                    move.dataAppName);
11453            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11454            synchronized (mInstallLock) {
11455                // Clean up both app data and code
11456                removeDataDirsLI(volumeUuid, move.packageName);
11457                if (codeFile.isDirectory()) {
11458                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11459                } else {
11460                    codeFile.delete();
11461                }
11462            }
11463            return true;
11464        }
11465
11466        void cleanUpResourcesLI() {
11467            throw new UnsupportedOperationException();
11468        }
11469
11470        boolean doPostDeleteLI(boolean delete) {
11471            throw new UnsupportedOperationException();
11472        }
11473    }
11474
11475    static String getAsecPackageName(String packageCid) {
11476        int idx = packageCid.lastIndexOf("-");
11477        if (idx == -1) {
11478            return packageCid;
11479        }
11480        return packageCid.substring(0, idx);
11481    }
11482
11483    // Utility method used to create code paths based on package name and available index.
11484    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11485        String idxStr = "";
11486        int idx = 1;
11487        // Fall back to default value of idx=1 if prefix is not
11488        // part of oldCodePath
11489        if (oldCodePath != null) {
11490            String subStr = oldCodePath;
11491            // Drop the suffix right away
11492            if (suffix != null && subStr.endsWith(suffix)) {
11493                subStr = subStr.substring(0, subStr.length() - suffix.length());
11494            }
11495            // If oldCodePath already contains prefix find out the
11496            // ending index to either increment or decrement.
11497            int sidx = subStr.lastIndexOf(prefix);
11498            if (sidx != -1) {
11499                subStr = subStr.substring(sidx + prefix.length());
11500                if (subStr != null) {
11501                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11502                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11503                    }
11504                    try {
11505                        idx = Integer.parseInt(subStr);
11506                        if (idx <= 1) {
11507                            idx++;
11508                        } else {
11509                            idx--;
11510                        }
11511                    } catch(NumberFormatException e) {
11512                    }
11513                }
11514            }
11515        }
11516        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11517        return prefix + idxStr;
11518    }
11519
11520    private File getNextCodePath(File targetDir, String packageName) {
11521        int suffix = 1;
11522        File result;
11523        do {
11524            result = new File(targetDir, packageName + "-" + suffix);
11525            suffix++;
11526        } while (result.exists());
11527        return result;
11528    }
11529
11530    // Utility method that returns the relative package path with respect
11531    // to the installation directory. Like say for /data/data/com.test-1.apk
11532    // string com.test-1 is returned.
11533    static String deriveCodePathName(String codePath) {
11534        if (codePath == null) {
11535            return null;
11536        }
11537        final File codeFile = new File(codePath);
11538        final String name = codeFile.getName();
11539        if (codeFile.isDirectory()) {
11540            return name;
11541        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11542            final int lastDot = name.lastIndexOf('.');
11543            return name.substring(0, lastDot);
11544        } else {
11545            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11546            return null;
11547        }
11548    }
11549
11550    class PackageInstalledInfo {
11551        String name;
11552        int uid;
11553        // The set of users that originally had this package installed.
11554        int[] origUsers;
11555        // The set of users that now have this package installed.
11556        int[] newUsers;
11557        PackageParser.Package pkg;
11558        int returnCode;
11559        String returnMsg;
11560        PackageRemovedInfo removedInfo;
11561
11562        public void setError(int code, String msg) {
11563            returnCode = code;
11564            returnMsg = msg;
11565            Slog.w(TAG, msg);
11566        }
11567
11568        public void setError(String msg, PackageParserException e) {
11569            returnCode = e.error;
11570            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11571            Slog.w(TAG, msg, e);
11572        }
11573
11574        public void setError(String msg, PackageManagerException e) {
11575            returnCode = e.error;
11576            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11577            Slog.w(TAG, msg, e);
11578        }
11579
11580        // In some error cases we want to convey more info back to the observer
11581        String origPackage;
11582        String origPermission;
11583    }
11584
11585    /*
11586     * Install a non-existing package.
11587     */
11588    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11589            UserHandle user, String installerPackageName, String volumeUuid,
11590            PackageInstalledInfo res) {
11591        // Remember this for later, in case we need to rollback this install
11592        String pkgName = pkg.packageName;
11593
11594        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11595        final boolean dataDirExists = Environment
11596                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11597        synchronized(mPackages) {
11598            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11599                // A package with the same name is already installed, though
11600                // it has been renamed to an older name.  The package we
11601                // are trying to install should be installed as an update to
11602                // the existing one, but that has not been requested, so bail.
11603                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11604                        + " without first uninstalling package running as "
11605                        + mSettings.mRenamedPackages.get(pkgName));
11606                return;
11607            }
11608            if (mPackages.containsKey(pkgName)) {
11609                // Don't allow installation over an existing package with the same name.
11610                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11611                        + " without first uninstalling.");
11612                return;
11613            }
11614        }
11615
11616        try {
11617            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11618                    System.currentTimeMillis(), user);
11619
11620            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11621            // delete the partially installed application. the data directory will have to be
11622            // restored if it was already existing
11623            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11624                // remove package from internal structures.  Note that we want deletePackageX to
11625                // delete the package data and cache directories that it created in
11626                // scanPackageLocked, unless those directories existed before we even tried to
11627                // install.
11628                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11629                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11630                                res.removedInfo, true);
11631            }
11632
11633        } catch (PackageManagerException e) {
11634            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11635        }
11636    }
11637
11638    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11639        // Can't rotate keys during boot or if sharedUser.
11640        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11641                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11642            return false;
11643        }
11644        // app is using upgradeKeySets; make sure all are valid
11645        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11646        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11647        for (int i = 0; i < upgradeKeySets.length; i++) {
11648            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11649                Slog.wtf(TAG, "Package "
11650                         + (oldPs.name != null ? oldPs.name : "<null>")
11651                         + " contains upgrade-key-set reference to unknown key-set: "
11652                         + upgradeKeySets[i]
11653                         + " reverting to signatures check.");
11654                return false;
11655            }
11656        }
11657        return true;
11658    }
11659
11660    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11661        // Upgrade keysets are being used.  Determine if new package has a superset of the
11662        // required keys.
11663        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11664        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11665        for (int i = 0; i < upgradeKeySets.length; i++) {
11666            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11667            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11668                return true;
11669            }
11670        }
11671        return false;
11672    }
11673
11674    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11675            UserHandle user, String installerPackageName, String volumeUuid,
11676            PackageInstalledInfo res) {
11677        final PackageParser.Package oldPackage;
11678        final String pkgName = pkg.packageName;
11679        final int[] allUsers;
11680        final boolean[] perUserInstalled;
11681        final boolean weFroze;
11682
11683        // First find the old package info and check signatures
11684        synchronized(mPackages) {
11685            oldPackage = mPackages.get(pkgName);
11686            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11687            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11688            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11689                if(!checkUpgradeKeySetLP(ps, pkg)) {
11690                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11691                            "New package not signed by keys specified by upgrade-keysets: "
11692                            + pkgName);
11693                    return;
11694                }
11695            } else {
11696                // default to original signature matching
11697                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11698                    != PackageManager.SIGNATURE_MATCH) {
11699                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11700                            "New package has a different signature: " + pkgName);
11701                    return;
11702                }
11703            }
11704
11705            // In case of rollback, remember per-user/profile install state
11706            allUsers = sUserManager.getUserIds();
11707            perUserInstalled = new boolean[allUsers.length];
11708            for (int i = 0; i < allUsers.length; i++) {
11709                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11710            }
11711
11712            // Mark the app as frozen to prevent launching during the upgrade
11713            // process, and then kill all running instances
11714            if (!ps.frozen) {
11715                ps.frozen = true;
11716                weFroze = true;
11717            } else {
11718                weFroze = false;
11719            }
11720        }
11721
11722        // Now that we're guarded by frozen state, kill app during upgrade
11723        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11724
11725        try {
11726            boolean sysPkg = (isSystemApp(oldPackage));
11727            if (sysPkg) {
11728                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11729                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11730            } else {
11731                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11732                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11733            }
11734        } finally {
11735            // Regardless of success or failure of upgrade steps above, always
11736            // unfreeze the package if we froze it
11737            if (weFroze) {
11738                unfreezePackage(pkgName);
11739            }
11740        }
11741    }
11742
11743    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11744            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11745            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11746            String volumeUuid, PackageInstalledInfo res) {
11747        String pkgName = deletedPackage.packageName;
11748        boolean deletedPkg = true;
11749        boolean updatedSettings = false;
11750
11751        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11752                + deletedPackage);
11753        long origUpdateTime;
11754        if (pkg.mExtras != null) {
11755            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11756        } else {
11757            origUpdateTime = 0;
11758        }
11759
11760        // First delete the existing package while retaining the data directory
11761        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11762                res.removedInfo, true)) {
11763            // If the existing package wasn't successfully deleted
11764            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11765            deletedPkg = false;
11766        } else {
11767            // Successfully deleted the old package; proceed with replace.
11768
11769            // If deleted package lived in a container, give users a chance to
11770            // relinquish resources before killing.
11771            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11772                if (DEBUG_INSTALL) {
11773                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11774                }
11775                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11776                final ArrayList<String> pkgList = new ArrayList<String>(1);
11777                pkgList.add(deletedPackage.applicationInfo.packageName);
11778                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11779            }
11780
11781            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11782            try {
11783                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11784                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11785                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11786                        perUserInstalled, res, user);
11787                updatedSettings = true;
11788            } catch (PackageManagerException e) {
11789                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11790            }
11791        }
11792
11793        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11794            // remove package from internal structures.  Note that we want deletePackageX to
11795            // delete the package data and cache directories that it created in
11796            // scanPackageLocked, unless those directories existed before we even tried to
11797            // install.
11798            if(updatedSettings) {
11799                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11800                deletePackageLI(
11801                        pkgName, null, true, allUsers, perUserInstalled,
11802                        PackageManager.DELETE_KEEP_DATA,
11803                                res.removedInfo, true);
11804            }
11805            // Since we failed to install the new package we need to restore the old
11806            // package that we deleted.
11807            if (deletedPkg) {
11808                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11809                File restoreFile = new File(deletedPackage.codePath);
11810                // Parse old package
11811                boolean oldExternal = isExternal(deletedPackage);
11812                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11813                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11814                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11815                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11816                try {
11817                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11818                } catch (PackageManagerException e) {
11819                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11820                            + e.getMessage());
11821                    return;
11822                }
11823                // Restore of old package succeeded. Update permissions.
11824                // writer
11825                synchronized (mPackages) {
11826                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11827                            UPDATE_PERMISSIONS_ALL);
11828                    // can downgrade to reader
11829                    mSettings.writeLPr();
11830                }
11831                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11832            }
11833        }
11834    }
11835
11836    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11837            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11838            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11839            String volumeUuid, PackageInstalledInfo res) {
11840        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11841                + ", old=" + deletedPackage);
11842        boolean disabledSystem = false;
11843        boolean updatedSettings = false;
11844        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11845        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11846                != 0) {
11847            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11848        }
11849        String packageName = deletedPackage.packageName;
11850        if (packageName == null) {
11851            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11852                    "Attempt to delete null packageName.");
11853            return;
11854        }
11855        PackageParser.Package oldPkg;
11856        PackageSetting oldPkgSetting;
11857        // reader
11858        synchronized (mPackages) {
11859            oldPkg = mPackages.get(packageName);
11860            oldPkgSetting = mSettings.mPackages.get(packageName);
11861            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11862                    (oldPkgSetting == null)) {
11863                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11864                        "Couldn't find package:" + packageName + " information");
11865                return;
11866            }
11867        }
11868
11869        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11870        res.removedInfo.removedPackage = packageName;
11871        // Remove existing system package
11872        removePackageLI(oldPkgSetting, true);
11873        // writer
11874        synchronized (mPackages) {
11875            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11876            if (!disabledSystem && deletedPackage != null) {
11877                // We didn't need to disable the .apk as a current system package,
11878                // which means we are replacing another update that is already
11879                // installed.  We need to make sure to delete the older one's .apk.
11880                res.removedInfo.args = createInstallArgsForExisting(0,
11881                        deletedPackage.applicationInfo.getCodePath(),
11882                        deletedPackage.applicationInfo.getResourcePath(),
11883                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11884            } else {
11885                res.removedInfo.args = null;
11886            }
11887        }
11888
11889        // Successfully disabled the old package. Now proceed with re-installation
11890        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11891
11892        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11893        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11894
11895        PackageParser.Package newPackage = null;
11896        try {
11897            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11898            if (newPackage.mExtras != null) {
11899                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11900                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11901                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11902
11903                // is the update attempting to change shared user? that isn't going to work...
11904                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11905                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11906                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11907                            + " to " + newPkgSetting.sharedUser);
11908                    updatedSettings = true;
11909                }
11910            }
11911
11912            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11913                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11914                        perUserInstalled, res, user);
11915                updatedSettings = true;
11916            }
11917
11918        } catch (PackageManagerException e) {
11919            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11920        }
11921
11922        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11923            // Re installation failed. Restore old information
11924            // Remove new pkg information
11925            if (newPackage != null) {
11926                removeInstalledPackageLI(newPackage, true);
11927            }
11928            // Add back the old system package
11929            try {
11930                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11931            } catch (PackageManagerException e) {
11932                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11933            }
11934            // Restore the old system information in Settings
11935            synchronized (mPackages) {
11936                if (disabledSystem) {
11937                    mSettings.enableSystemPackageLPw(packageName);
11938                }
11939                if (updatedSettings) {
11940                    mSettings.setInstallerPackageName(packageName,
11941                            oldPkgSetting.installerPackageName);
11942                }
11943                mSettings.writeLPr();
11944            }
11945        }
11946    }
11947
11948    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11949            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11950            UserHandle user) {
11951        String pkgName = newPackage.packageName;
11952        synchronized (mPackages) {
11953            //write settings. the installStatus will be incomplete at this stage.
11954            //note that the new package setting would have already been
11955            //added to mPackages. It hasn't been persisted yet.
11956            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11957            mSettings.writeLPr();
11958        }
11959
11960        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11961
11962        synchronized (mPackages) {
11963            updatePermissionsLPw(newPackage.packageName, newPackage,
11964                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11965                            ? UPDATE_PERMISSIONS_ALL : 0));
11966            // For system-bundled packages, we assume that installing an upgraded version
11967            // of the package implies that the user actually wants to run that new code,
11968            // so we enable the package.
11969            PackageSetting ps = mSettings.mPackages.get(pkgName);
11970            if (ps != null) {
11971                if (isSystemApp(newPackage)) {
11972                    // NB: implicit assumption that system package upgrades apply to all users
11973                    if (DEBUG_INSTALL) {
11974                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11975                    }
11976                    if (res.origUsers != null) {
11977                        for (int userHandle : res.origUsers) {
11978                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11979                                    userHandle, installerPackageName);
11980                        }
11981                    }
11982                    // Also convey the prior install/uninstall state
11983                    if (allUsers != null && perUserInstalled != null) {
11984                        for (int i = 0; i < allUsers.length; i++) {
11985                            if (DEBUG_INSTALL) {
11986                                Slog.d(TAG, "    user " + allUsers[i]
11987                                        + " => " + perUserInstalled[i]);
11988                            }
11989                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11990                        }
11991                        // these install state changes will be persisted in the
11992                        // upcoming call to mSettings.writeLPr().
11993                    }
11994                }
11995                // It's implied that when a user requests installation, they want the app to be
11996                // installed and enabled.
11997                int userId = user.getIdentifier();
11998                if (userId != UserHandle.USER_ALL) {
11999                    ps.setInstalled(true, userId);
12000                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12001                }
12002            }
12003            res.name = pkgName;
12004            res.uid = newPackage.applicationInfo.uid;
12005            res.pkg = newPackage;
12006            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12007            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12008            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12009            //to update install status
12010            mSettings.writeLPr();
12011        }
12012    }
12013
12014    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12015        final int installFlags = args.installFlags;
12016        final String installerPackageName = args.installerPackageName;
12017        final String volumeUuid = args.volumeUuid;
12018        final File tmpPackageFile = new File(args.getCodePath());
12019        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12020        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12021                || (args.volumeUuid != null));
12022        boolean replace = false;
12023        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12024        if (args.move != null) {
12025            // moving a complete application; perfom an initial scan on the new install location
12026            scanFlags |= SCAN_INITIAL;
12027        }
12028        // Result object to be returned
12029        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12030
12031        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12032        // Retrieve PackageSettings and parse package
12033        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12034                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12035                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12036        PackageParser pp = new PackageParser();
12037        pp.setSeparateProcesses(mSeparateProcesses);
12038        pp.setDisplayMetrics(mMetrics);
12039
12040        final PackageParser.Package pkg;
12041        try {
12042            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12043        } catch (PackageParserException e) {
12044            res.setError("Failed parse during installPackageLI", e);
12045            return;
12046        }
12047
12048        // Mark that we have an install time CPU ABI override.
12049        pkg.cpuAbiOverride = args.abiOverride;
12050
12051        String pkgName = res.name = pkg.packageName;
12052        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12053            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12054                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12055                return;
12056            }
12057        }
12058
12059        try {
12060            pp.collectCertificates(pkg, parseFlags);
12061            pp.collectManifestDigest(pkg);
12062        } catch (PackageParserException e) {
12063            res.setError("Failed collect during installPackageLI", e);
12064            return;
12065        }
12066
12067        /* If the installer passed in a manifest digest, compare it now. */
12068        if (args.manifestDigest != null) {
12069            if (DEBUG_INSTALL) {
12070                final String parsedManifest = pkg.manifestDigest == null ? "null"
12071                        : pkg.manifestDigest.toString();
12072                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12073                        + parsedManifest);
12074            }
12075
12076            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12077                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12078                return;
12079            }
12080        } else if (DEBUG_INSTALL) {
12081            final String parsedManifest = pkg.manifestDigest == null
12082                    ? "null" : pkg.manifestDigest.toString();
12083            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12084        }
12085
12086        // Get rid of all references to package scan path via parser.
12087        pp = null;
12088        String oldCodePath = null;
12089        boolean systemApp = false;
12090        synchronized (mPackages) {
12091            // Check if installing already existing package
12092            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12093                String oldName = mSettings.mRenamedPackages.get(pkgName);
12094                if (pkg.mOriginalPackages != null
12095                        && pkg.mOriginalPackages.contains(oldName)
12096                        && mPackages.containsKey(oldName)) {
12097                    // This package is derived from an original package,
12098                    // and this device has been updating from that original
12099                    // name.  We must continue using the original name, so
12100                    // rename the new package here.
12101                    pkg.setPackageName(oldName);
12102                    pkgName = pkg.packageName;
12103                    replace = true;
12104                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12105                            + oldName + " pkgName=" + pkgName);
12106                } else if (mPackages.containsKey(pkgName)) {
12107                    // This package, under its official name, already exists
12108                    // on the device; we should replace it.
12109                    replace = true;
12110                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12111                }
12112
12113                // Prevent apps opting out from runtime permissions
12114                if (replace) {
12115                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12116                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12117                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12118                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12119                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12120                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12121                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12122                                        + " doesn't support runtime permissions but the old"
12123                                        + " target SDK " + oldTargetSdk + " does.");
12124                        return;
12125                    }
12126                }
12127            }
12128
12129            PackageSetting ps = mSettings.mPackages.get(pkgName);
12130            if (ps != null) {
12131                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12132
12133                // Quick sanity check that we're signed correctly if updating;
12134                // we'll check this again later when scanning, but we want to
12135                // bail early here before tripping over redefined permissions.
12136                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12137                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12138                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12139                                + pkg.packageName + " upgrade keys do not match the "
12140                                + "previously installed version");
12141                        return;
12142                    }
12143                } else {
12144                    try {
12145                        verifySignaturesLP(ps, pkg);
12146                    } catch (PackageManagerException e) {
12147                        res.setError(e.error, e.getMessage());
12148                        return;
12149                    }
12150                }
12151
12152                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12153                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12154                    systemApp = (ps.pkg.applicationInfo.flags &
12155                            ApplicationInfo.FLAG_SYSTEM) != 0;
12156                }
12157                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12158            }
12159
12160            // Check whether the newly-scanned package wants to define an already-defined perm
12161            int N = pkg.permissions.size();
12162            for (int i = N-1; i >= 0; i--) {
12163                PackageParser.Permission perm = pkg.permissions.get(i);
12164                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12165                if (bp != null) {
12166                    // If the defining package is signed with our cert, it's okay.  This
12167                    // also includes the "updating the same package" case, of course.
12168                    // "updating same package" could also involve key-rotation.
12169                    final boolean sigsOk;
12170                    if (bp.sourcePackage.equals(pkg.packageName)
12171                            && (bp.packageSetting instanceof PackageSetting)
12172                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12173                                    scanFlags))) {
12174                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12175                    } else {
12176                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12177                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12178                    }
12179                    if (!sigsOk) {
12180                        // If the owning package is the system itself, we log but allow
12181                        // install to proceed; we fail the install on all other permission
12182                        // redefinitions.
12183                        if (!bp.sourcePackage.equals("android")) {
12184                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12185                                    + pkg.packageName + " attempting to redeclare permission "
12186                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12187                            res.origPermission = perm.info.name;
12188                            res.origPackage = bp.sourcePackage;
12189                            return;
12190                        } else {
12191                            Slog.w(TAG, "Package " + pkg.packageName
12192                                    + " attempting to redeclare system permission "
12193                                    + perm.info.name + "; ignoring new declaration");
12194                            pkg.permissions.remove(i);
12195                        }
12196                    }
12197                }
12198            }
12199
12200        }
12201
12202        if (systemApp && onExternal) {
12203            // Disable updates to system apps on sdcard
12204            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12205                    "Cannot install updates to system apps on sdcard");
12206            return;
12207        }
12208
12209        if (args.move != null) {
12210            // We did an in-place move, so dex is ready to roll
12211            scanFlags |= SCAN_NO_DEX;
12212            scanFlags |= SCAN_MOVE;
12213        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12214            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12215            scanFlags |= SCAN_NO_DEX;
12216
12217            try {
12218                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12219                        true /* extract libs */);
12220            } catch (PackageManagerException pme) {
12221                Slog.e(TAG, "Error deriving application ABI", pme);
12222                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12223                return;
12224            }
12225
12226            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12227            int result = mPackageDexOptimizer
12228                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12229                            false /* defer */, false /* inclDependencies */);
12230            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12231                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12232                return;
12233            }
12234        }
12235
12236        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12237            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12238            return;
12239        }
12240
12241        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12242
12243        if (replace) {
12244            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12245                    installerPackageName, volumeUuid, res);
12246        } else {
12247            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12248                    args.user, installerPackageName, volumeUuid, res);
12249        }
12250        synchronized (mPackages) {
12251            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12252            if (ps != null) {
12253                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12254            }
12255        }
12256    }
12257
12258    private void startIntentFilterVerifications(int userId, boolean replacing,
12259            PackageParser.Package pkg) {
12260        if (mIntentFilterVerifierComponent == null) {
12261            Slog.w(TAG, "No IntentFilter verification will not be done as "
12262                    + "there is no IntentFilterVerifier available!");
12263            return;
12264        }
12265
12266        final int verifierUid = getPackageUid(
12267                mIntentFilterVerifierComponent.getPackageName(),
12268                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12269
12270        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12271        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12272        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12273        mHandler.sendMessage(msg);
12274    }
12275
12276    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12277            PackageParser.Package pkg) {
12278        int size = pkg.activities.size();
12279        if (size == 0) {
12280            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12281                    "No activity, so no need to verify any IntentFilter!");
12282            return;
12283        }
12284
12285        final boolean hasDomainURLs = hasDomainURLs(pkg);
12286        if (!hasDomainURLs) {
12287            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12288                    "No domain URLs, so no need to verify any IntentFilter!");
12289            return;
12290        }
12291
12292        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12293                + " if any IntentFilter from the " + size
12294                + " Activities needs verification ...");
12295
12296        int count = 0;
12297        final String packageName = pkg.packageName;
12298
12299        synchronized (mPackages) {
12300            // If this is a new install and we see that we've already run verification for this
12301            // package, we have nothing to do: it means the state was restored from backup.
12302            if (!replacing) {
12303                IntentFilterVerificationInfo ivi =
12304                        mSettings.getIntentFilterVerificationLPr(packageName);
12305                if (ivi != null) {
12306                    if (DEBUG_DOMAIN_VERIFICATION) {
12307                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12308                                + ivi.getStatusString());
12309                    }
12310                    return;
12311                }
12312            }
12313
12314            // If any filters need to be verified, then all need to be.
12315            boolean needToVerify = false;
12316            for (PackageParser.Activity a : pkg.activities) {
12317                for (ActivityIntentInfo filter : a.intents) {
12318                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12319                        if (DEBUG_DOMAIN_VERIFICATION) {
12320                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12321                        }
12322                        needToVerify = true;
12323                        break;
12324                    }
12325                }
12326            }
12327
12328            if (needToVerify) {
12329                final int verificationId = mIntentFilterVerificationToken++;
12330                for (PackageParser.Activity a : pkg.activities) {
12331                    for (ActivityIntentInfo filter : a.intents) {
12332                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12333                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12334                                    "Verification needed for IntentFilter:" + filter.toString());
12335                            mIntentFilterVerifier.addOneIntentFilterVerification(
12336                                    verifierUid, userId, verificationId, filter, packageName);
12337                            count++;
12338                        }
12339                    }
12340                }
12341            }
12342        }
12343
12344        if (count > 0) {
12345            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12346                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12347                    +  " for userId:" + userId);
12348            mIntentFilterVerifier.startVerifications(userId);
12349        } else {
12350            if (DEBUG_DOMAIN_VERIFICATION) {
12351                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12352            }
12353        }
12354    }
12355
12356    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12357        final ComponentName cn  = filter.activity.getComponentName();
12358        final String packageName = cn.getPackageName();
12359
12360        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12361                packageName);
12362        if (ivi == null) {
12363            return true;
12364        }
12365        int status = ivi.getStatus();
12366        switch (status) {
12367            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12368            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12369                return true;
12370
12371            default:
12372                // Nothing to do
12373                return false;
12374        }
12375    }
12376
12377    private static boolean isMultiArch(PackageSetting ps) {
12378        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12379    }
12380
12381    private static boolean isMultiArch(ApplicationInfo info) {
12382        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12383    }
12384
12385    private static boolean isExternal(PackageParser.Package pkg) {
12386        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12387    }
12388
12389    private static boolean isExternal(PackageSetting ps) {
12390        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12391    }
12392
12393    private static boolean isExternal(ApplicationInfo info) {
12394        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12395    }
12396
12397    private static boolean isSystemApp(PackageParser.Package pkg) {
12398        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12399    }
12400
12401    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12402        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12403    }
12404
12405    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12406        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12407    }
12408
12409    private static boolean isSystemApp(PackageSetting ps) {
12410        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12411    }
12412
12413    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12414        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12415    }
12416
12417    private int packageFlagsToInstallFlags(PackageSetting ps) {
12418        int installFlags = 0;
12419        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12420            // This existing package was an external ASEC install when we have
12421            // the external flag without a UUID
12422            installFlags |= PackageManager.INSTALL_EXTERNAL;
12423        }
12424        if (ps.isForwardLocked()) {
12425            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12426        }
12427        return installFlags;
12428    }
12429
12430    private void deleteTempPackageFiles() {
12431        final FilenameFilter filter = new FilenameFilter() {
12432            public boolean accept(File dir, String name) {
12433                return name.startsWith("vmdl") && name.endsWith(".tmp");
12434            }
12435        };
12436        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12437            file.delete();
12438        }
12439    }
12440
12441    @Override
12442    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12443            int flags) {
12444        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12445                flags);
12446    }
12447
12448    @Override
12449    public void deletePackage(final String packageName,
12450            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12451        mContext.enforceCallingOrSelfPermission(
12452                android.Manifest.permission.DELETE_PACKAGES, null);
12453        Preconditions.checkNotNull(packageName);
12454        Preconditions.checkNotNull(observer);
12455        final int uid = Binder.getCallingUid();
12456        if (UserHandle.getUserId(uid) != userId) {
12457            mContext.enforceCallingPermission(
12458                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12459                    "deletePackage for user " + userId);
12460        }
12461        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12462            try {
12463                observer.onPackageDeleted(packageName,
12464                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12465            } catch (RemoteException re) {
12466            }
12467            return;
12468        }
12469
12470        boolean uninstallBlocked = false;
12471        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12472            int[] users = sUserManager.getUserIds();
12473            for (int i = 0; i < users.length; ++i) {
12474                if (getBlockUninstallForUser(packageName, users[i])) {
12475                    uninstallBlocked = true;
12476                    break;
12477                }
12478            }
12479        } else {
12480            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12481        }
12482        if (uninstallBlocked) {
12483            try {
12484                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12485                        null);
12486            } catch (RemoteException re) {
12487            }
12488            return;
12489        }
12490
12491        if (DEBUG_REMOVE) {
12492            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12493        }
12494        // Queue up an async operation since the package deletion may take a little while.
12495        mHandler.post(new Runnable() {
12496            public void run() {
12497                mHandler.removeCallbacks(this);
12498                final int returnCode = deletePackageX(packageName, userId, flags);
12499                if (observer != null) {
12500                    try {
12501                        observer.onPackageDeleted(packageName, returnCode, null);
12502                    } catch (RemoteException e) {
12503                        Log.i(TAG, "Observer no longer exists.");
12504                    } //end catch
12505                } //end if
12506            } //end run
12507        });
12508    }
12509
12510    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12511        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12512                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12513        try {
12514            if (dpm != null) {
12515                if (dpm.isDeviceOwner(packageName)) {
12516                    return true;
12517                }
12518                int[] users;
12519                if (userId == UserHandle.USER_ALL) {
12520                    users = sUserManager.getUserIds();
12521                } else {
12522                    users = new int[]{userId};
12523                }
12524                for (int i = 0; i < users.length; ++i) {
12525                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12526                        return true;
12527                    }
12528                }
12529            }
12530        } catch (RemoteException e) {
12531        }
12532        return false;
12533    }
12534
12535    /**
12536     *  This method is an internal method that could be get invoked either
12537     *  to delete an installed package or to clean up a failed installation.
12538     *  After deleting an installed package, a broadcast is sent to notify any
12539     *  listeners that the package has been installed. For cleaning up a failed
12540     *  installation, the broadcast is not necessary since the package's
12541     *  installation wouldn't have sent the initial broadcast either
12542     *  The key steps in deleting a package are
12543     *  deleting the package information in internal structures like mPackages,
12544     *  deleting the packages base directories through installd
12545     *  updating mSettings to reflect current status
12546     *  persisting settings for later use
12547     *  sending a broadcast if necessary
12548     */
12549    private int deletePackageX(String packageName, int userId, int flags) {
12550        final PackageRemovedInfo info = new PackageRemovedInfo();
12551        final boolean res;
12552
12553        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12554                ? UserHandle.ALL : new UserHandle(userId);
12555
12556        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12557            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12558            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12559        }
12560
12561        boolean removedForAllUsers = false;
12562        boolean systemUpdate = false;
12563
12564        // for the uninstall-updates case and restricted profiles, remember the per-
12565        // userhandle installed state
12566        int[] allUsers;
12567        boolean[] perUserInstalled;
12568        synchronized (mPackages) {
12569            PackageSetting ps = mSettings.mPackages.get(packageName);
12570            allUsers = sUserManager.getUserIds();
12571            perUserInstalled = new boolean[allUsers.length];
12572            for (int i = 0; i < allUsers.length; i++) {
12573                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12574            }
12575        }
12576
12577        synchronized (mInstallLock) {
12578            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12579            res = deletePackageLI(packageName, removeForUser,
12580                    true, allUsers, perUserInstalled,
12581                    flags | REMOVE_CHATTY, info, true);
12582            systemUpdate = info.isRemovedPackageSystemUpdate;
12583            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12584                removedForAllUsers = true;
12585            }
12586            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12587                    + " removedForAllUsers=" + removedForAllUsers);
12588        }
12589
12590        if (res) {
12591            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12592
12593            // If the removed package was a system update, the old system package
12594            // was re-enabled; we need to broadcast this information
12595            if (systemUpdate) {
12596                Bundle extras = new Bundle(1);
12597                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12598                        ? info.removedAppId : info.uid);
12599                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12600
12601                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12602                        extras, null, null, null);
12603                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12604                        extras, null, null, null);
12605                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12606                        null, packageName, null, null);
12607            }
12608        }
12609        // Force a gc here.
12610        Runtime.getRuntime().gc();
12611        // Delete the resources here after sending the broadcast to let
12612        // other processes clean up before deleting resources.
12613        if (info.args != null) {
12614            synchronized (mInstallLock) {
12615                info.args.doPostDeleteLI(true);
12616            }
12617        }
12618
12619        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12620    }
12621
12622    class PackageRemovedInfo {
12623        String removedPackage;
12624        int uid = -1;
12625        int removedAppId = -1;
12626        int[] removedUsers = null;
12627        boolean isRemovedPackageSystemUpdate = false;
12628        // Clean up resources deleted packages.
12629        InstallArgs args = null;
12630
12631        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12632            Bundle extras = new Bundle(1);
12633            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12634            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12635            if (replacing) {
12636                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12637            }
12638            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12639            if (removedPackage != null) {
12640                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12641                        extras, null, null, removedUsers);
12642                if (fullRemove && !replacing) {
12643                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12644                            extras, null, null, removedUsers);
12645                }
12646            }
12647            if (removedAppId >= 0) {
12648                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12649                        removedUsers);
12650            }
12651        }
12652    }
12653
12654    /*
12655     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12656     * flag is not set, the data directory is removed as well.
12657     * make sure this flag is set for partially installed apps. If not its meaningless to
12658     * delete a partially installed application.
12659     */
12660    private void removePackageDataLI(PackageSetting ps,
12661            int[] allUserHandles, boolean[] perUserInstalled,
12662            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12663        String packageName = ps.name;
12664        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12665        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12666        // Retrieve object to delete permissions for shared user later on
12667        final PackageSetting deletedPs;
12668        // reader
12669        synchronized (mPackages) {
12670            deletedPs = mSettings.mPackages.get(packageName);
12671            if (outInfo != null) {
12672                outInfo.removedPackage = packageName;
12673                outInfo.removedUsers = deletedPs != null
12674                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12675                        : null;
12676            }
12677        }
12678        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12679            removeDataDirsLI(ps.volumeUuid, packageName);
12680            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12681        }
12682        // writer
12683        synchronized (mPackages) {
12684            if (deletedPs != null) {
12685                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12686                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12687                    clearDefaultBrowserIfNeeded(packageName);
12688                    if (outInfo != null) {
12689                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12690                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12691                    }
12692                    updatePermissionsLPw(deletedPs.name, null, 0);
12693                    if (deletedPs.sharedUser != null) {
12694                        // Remove permissions associated with package. Since runtime
12695                        // permissions are per user we have to kill the removed package
12696                        // or packages running under the shared user of the removed
12697                        // package if revoking the permissions requested only by the removed
12698                        // package is successful and this causes a change in gids.
12699                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12700                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12701                                    userId);
12702                            if (userIdToKill == UserHandle.USER_ALL
12703                                    || userIdToKill >= UserHandle.USER_OWNER) {
12704                                // If gids changed for this user, kill all affected packages.
12705                                mHandler.post(new Runnable() {
12706                                    @Override
12707                                    public void run() {
12708                                        // This has to happen with no lock held.
12709                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12710                                                KILL_APP_REASON_GIDS_CHANGED);
12711                                    }
12712                                });
12713                                break;
12714                            }
12715                        }
12716                    }
12717                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12718                }
12719                // make sure to preserve per-user disabled state if this removal was just
12720                // a downgrade of a system app to the factory package
12721                if (allUserHandles != null && perUserInstalled != null) {
12722                    if (DEBUG_REMOVE) {
12723                        Slog.d(TAG, "Propagating install state across downgrade");
12724                    }
12725                    for (int i = 0; i < allUserHandles.length; i++) {
12726                        if (DEBUG_REMOVE) {
12727                            Slog.d(TAG, "    user " + allUserHandles[i]
12728                                    + " => " + perUserInstalled[i]);
12729                        }
12730                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12731                    }
12732                }
12733            }
12734            // can downgrade to reader
12735            if (writeSettings) {
12736                // Save settings now
12737                mSettings.writeLPr();
12738            }
12739        }
12740        if (outInfo != null) {
12741            // A user ID was deleted here. Go through all users and remove it
12742            // from KeyStore.
12743            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12744        }
12745    }
12746
12747    static boolean locationIsPrivileged(File path) {
12748        try {
12749            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12750                    .getCanonicalPath();
12751            return path.getCanonicalPath().startsWith(privilegedAppDir);
12752        } catch (IOException e) {
12753            Slog.e(TAG, "Unable to access code path " + path);
12754        }
12755        return false;
12756    }
12757
12758    /*
12759     * Tries to delete system package.
12760     */
12761    private boolean deleteSystemPackageLI(PackageSetting newPs,
12762            int[] allUserHandles, boolean[] perUserInstalled,
12763            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12764        final boolean applyUserRestrictions
12765                = (allUserHandles != null) && (perUserInstalled != null);
12766        PackageSetting disabledPs = null;
12767        // Confirm if the system package has been updated
12768        // An updated system app can be deleted. This will also have to restore
12769        // the system pkg from system partition
12770        // reader
12771        synchronized (mPackages) {
12772            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12773        }
12774        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12775                + " disabledPs=" + disabledPs);
12776        if (disabledPs == null) {
12777            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12778            return false;
12779        } else if (DEBUG_REMOVE) {
12780            Slog.d(TAG, "Deleting system pkg from data partition");
12781        }
12782        if (DEBUG_REMOVE) {
12783            if (applyUserRestrictions) {
12784                Slog.d(TAG, "Remembering install states:");
12785                for (int i = 0; i < allUserHandles.length; i++) {
12786                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12787                }
12788            }
12789        }
12790        // Delete the updated package
12791        outInfo.isRemovedPackageSystemUpdate = true;
12792        if (disabledPs.versionCode < newPs.versionCode) {
12793            // Delete data for downgrades
12794            flags &= ~PackageManager.DELETE_KEEP_DATA;
12795        } else {
12796            // Preserve data by setting flag
12797            flags |= PackageManager.DELETE_KEEP_DATA;
12798        }
12799        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12800                allUserHandles, perUserInstalled, outInfo, writeSettings);
12801        if (!ret) {
12802            return false;
12803        }
12804        // writer
12805        synchronized (mPackages) {
12806            // Reinstate the old system package
12807            mSettings.enableSystemPackageLPw(newPs.name);
12808            // Remove any native libraries from the upgraded package.
12809            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12810        }
12811        // Install the system package
12812        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12813        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12814        if (locationIsPrivileged(disabledPs.codePath)) {
12815            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12816        }
12817
12818        final PackageParser.Package newPkg;
12819        try {
12820            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12821        } catch (PackageManagerException e) {
12822            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12823            return false;
12824        }
12825
12826        // writer
12827        synchronized (mPackages) {
12828            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12829
12830            // Propagate the permissions state as we do want to drop on the floor
12831            // runtime permissions. The update permissions method below will take
12832            // care of removing obsolete permissions and grant install permissions.
12833            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12834            updatePermissionsLPw(newPkg.packageName, newPkg,
12835                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12836
12837            if (applyUserRestrictions) {
12838                if (DEBUG_REMOVE) {
12839                    Slog.d(TAG, "Propagating install state across reinstall");
12840                }
12841                for (int i = 0; i < allUserHandles.length; i++) {
12842                    if (DEBUG_REMOVE) {
12843                        Slog.d(TAG, "    user " + allUserHandles[i]
12844                                + " => " + perUserInstalled[i]);
12845                    }
12846                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12847                }
12848                // Regardless of writeSettings we need to ensure that this restriction
12849                // state propagation is persisted
12850                mSettings.writeAllUsersPackageRestrictionsLPr();
12851            }
12852            // can downgrade to reader here
12853            if (writeSettings) {
12854                mSettings.writeLPr();
12855            }
12856        }
12857        return true;
12858    }
12859
12860    private boolean deleteInstalledPackageLI(PackageSetting ps,
12861            boolean deleteCodeAndResources, int flags,
12862            int[] allUserHandles, boolean[] perUserInstalled,
12863            PackageRemovedInfo outInfo, boolean writeSettings) {
12864        if (outInfo != null) {
12865            outInfo.uid = ps.appId;
12866        }
12867
12868        // Delete package data from internal structures and also remove data if flag is set
12869        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12870
12871        // Delete application code and resources
12872        if (deleteCodeAndResources && (outInfo != null)) {
12873            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12874                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12875            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12876        }
12877        return true;
12878    }
12879
12880    @Override
12881    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12882            int userId) {
12883        mContext.enforceCallingOrSelfPermission(
12884                android.Manifest.permission.DELETE_PACKAGES, null);
12885        synchronized (mPackages) {
12886            PackageSetting ps = mSettings.mPackages.get(packageName);
12887            if (ps == null) {
12888                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12889                return false;
12890            }
12891            if (!ps.getInstalled(userId)) {
12892                // Can't block uninstall for an app that is not installed or enabled.
12893                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12894                return false;
12895            }
12896            ps.setBlockUninstall(blockUninstall, userId);
12897            mSettings.writePackageRestrictionsLPr(userId);
12898        }
12899        return true;
12900    }
12901
12902    @Override
12903    public boolean getBlockUninstallForUser(String packageName, int userId) {
12904        synchronized (mPackages) {
12905            PackageSetting ps = mSettings.mPackages.get(packageName);
12906            if (ps == null) {
12907                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12908                return false;
12909            }
12910            return ps.getBlockUninstall(userId);
12911        }
12912    }
12913
12914    /*
12915     * This method handles package deletion in general
12916     */
12917    private boolean deletePackageLI(String packageName, UserHandle user,
12918            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12919            int flags, PackageRemovedInfo outInfo,
12920            boolean writeSettings) {
12921        if (packageName == null) {
12922            Slog.w(TAG, "Attempt to delete null packageName.");
12923            return false;
12924        }
12925        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12926        PackageSetting ps;
12927        boolean dataOnly = false;
12928        int removeUser = -1;
12929        int appId = -1;
12930        synchronized (mPackages) {
12931            ps = mSettings.mPackages.get(packageName);
12932            if (ps == null) {
12933                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12934                return false;
12935            }
12936            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12937                    && user.getIdentifier() != UserHandle.USER_ALL) {
12938                // The caller is asking that the package only be deleted for a single
12939                // user.  To do this, we just mark its uninstalled state and delete
12940                // its data.  If this is a system app, we only allow this to happen if
12941                // they have set the special DELETE_SYSTEM_APP which requests different
12942                // semantics than normal for uninstalling system apps.
12943                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12944                ps.setUserState(user.getIdentifier(),
12945                        COMPONENT_ENABLED_STATE_DEFAULT,
12946                        false, //installed
12947                        true,  //stopped
12948                        true,  //notLaunched
12949                        false, //hidden
12950                        null, null, null,
12951                        false, // blockUninstall
12952                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12953                if (!isSystemApp(ps)) {
12954                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12955                        // Other user still have this package installed, so all
12956                        // we need to do is clear this user's data and save that
12957                        // it is uninstalled.
12958                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12959                        removeUser = user.getIdentifier();
12960                        appId = ps.appId;
12961                        scheduleWritePackageRestrictionsLocked(removeUser);
12962                    } else {
12963                        // We need to set it back to 'installed' so the uninstall
12964                        // broadcasts will be sent correctly.
12965                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12966                        ps.setInstalled(true, user.getIdentifier());
12967                    }
12968                } else {
12969                    // This is a system app, so we assume that the
12970                    // other users still have this package installed, so all
12971                    // we need to do is clear this user's data and save that
12972                    // it is uninstalled.
12973                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12974                    removeUser = user.getIdentifier();
12975                    appId = ps.appId;
12976                    scheduleWritePackageRestrictionsLocked(removeUser);
12977                }
12978            }
12979        }
12980
12981        if (removeUser >= 0) {
12982            // From above, we determined that we are deleting this only
12983            // for a single user.  Continue the work here.
12984            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12985            if (outInfo != null) {
12986                outInfo.removedPackage = packageName;
12987                outInfo.removedAppId = appId;
12988                outInfo.removedUsers = new int[] {removeUser};
12989            }
12990            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12991            removeKeystoreDataIfNeeded(removeUser, appId);
12992            schedulePackageCleaning(packageName, removeUser, false);
12993            synchronized (mPackages) {
12994                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12995                    scheduleWritePackageRestrictionsLocked(removeUser);
12996                }
12997                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
12998            }
12999            return true;
13000        }
13001
13002        if (dataOnly) {
13003            // Delete application data first
13004            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13005            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13006            return true;
13007        }
13008
13009        boolean ret = false;
13010        if (isSystemApp(ps)) {
13011            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13012            // When an updated system application is deleted we delete the existing resources as well and
13013            // fall back to existing code in system partition
13014            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13015                    flags, outInfo, writeSettings);
13016        } else {
13017            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13018            // Kill application pre-emptively especially for apps on sd.
13019            killApplication(packageName, ps.appId, "uninstall pkg");
13020            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13021                    allUserHandles, perUserInstalled,
13022                    outInfo, writeSettings);
13023        }
13024
13025        return ret;
13026    }
13027
13028    private final class ClearStorageConnection implements ServiceConnection {
13029        IMediaContainerService mContainerService;
13030
13031        @Override
13032        public void onServiceConnected(ComponentName name, IBinder service) {
13033            synchronized (this) {
13034                mContainerService = IMediaContainerService.Stub.asInterface(service);
13035                notifyAll();
13036            }
13037        }
13038
13039        @Override
13040        public void onServiceDisconnected(ComponentName name) {
13041        }
13042    }
13043
13044    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13045        final boolean mounted;
13046        if (Environment.isExternalStorageEmulated()) {
13047            mounted = true;
13048        } else {
13049            final String status = Environment.getExternalStorageState();
13050
13051            mounted = status.equals(Environment.MEDIA_MOUNTED)
13052                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13053        }
13054
13055        if (!mounted) {
13056            return;
13057        }
13058
13059        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13060        int[] users;
13061        if (userId == UserHandle.USER_ALL) {
13062            users = sUserManager.getUserIds();
13063        } else {
13064            users = new int[] { userId };
13065        }
13066        final ClearStorageConnection conn = new ClearStorageConnection();
13067        if (mContext.bindServiceAsUser(
13068                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13069            try {
13070                for (int curUser : users) {
13071                    long timeout = SystemClock.uptimeMillis() + 5000;
13072                    synchronized (conn) {
13073                        long now = SystemClock.uptimeMillis();
13074                        while (conn.mContainerService == null && now < timeout) {
13075                            try {
13076                                conn.wait(timeout - now);
13077                            } catch (InterruptedException e) {
13078                            }
13079                        }
13080                    }
13081                    if (conn.mContainerService == null) {
13082                        return;
13083                    }
13084
13085                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13086                    clearDirectory(conn.mContainerService,
13087                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13088                    if (allData) {
13089                        clearDirectory(conn.mContainerService,
13090                                userEnv.buildExternalStorageAppDataDirs(packageName));
13091                        clearDirectory(conn.mContainerService,
13092                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13093                    }
13094                }
13095            } finally {
13096                mContext.unbindService(conn);
13097            }
13098        }
13099    }
13100
13101    @Override
13102    public void clearApplicationUserData(final String packageName,
13103            final IPackageDataObserver observer, final int userId) {
13104        mContext.enforceCallingOrSelfPermission(
13105                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13106        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13107        // Queue up an async operation since the package deletion may take a little while.
13108        mHandler.post(new Runnable() {
13109            public void run() {
13110                mHandler.removeCallbacks(this);
13111                final boolean succeeded;
13112                synchronized (mInstallLock) {
13113                    succeeded = clearApplicationUserDataLI(packageName, userId);
13114                }
13115                clearExternalStorageDataSync(packageName, userId, true);
13116                if (succeeded) {
13117                    // invoke DeviceStorageMonitor's update method to clear any notifications
13118                    DeviceStorageMonitorInternal
13119                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13120                    if (dsm != null) {
13121                        dsm.checkMemory();
13122                    }
13123                }
13124                if(observer != null) {
13125                    try {
13126                        observer.onRemoveCompleted(packageName, succeeded);
13127                    } catch (RemoteException e) {
13128                        Log.i(TAG, "Observer no longer exists.");
13129                    }
13130                } //end if observer
13131            } //end run
13132        });
13133    }
13134
13135    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13136        if (packageName == null) {
13137            Slog.w(TAG, "Attempt to delete null packageName.");
13138            return false;
13139        }
13140
13141        // Try finding details about the requested package
13142        PackageParser.Package pkg;
13143        synchronized (mPackages) {
13144            pkg = mPackages.get(packageName);
13145            if (pkg == null) {
13146                final PackageSetting ps = mSettings.mPackages.get(packageName);
13147                if (ps != null) {
13148                    pkg = ps.pkg;
13149                }
13150            }
13151
13152            if (pkg == null) {
13153                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13154                return false;
13155            }
13156
13157            PackageSetting ps = (PackageSetting) pkg.mExtras;
13158            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13159        }
13160
13161        // Always delete data directories for package, even if we found no other
13162        // record of app. This helps users recover from UID mismatches without
13163        // resorting to a full data wipe.
13164        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13165        if (retCode < 0) {
13166            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13167            return false;
13168        }
13169
13170        final int appId = pkg.applicationInfo.uid;
13171        removeKeystoreDataIfNeeded(userId, appId);
13172
13173        // Create a native library symlink only if we have native libraries
13174        // and if the native libraries are 32 bit libraries. We do not provide
13175        // this symlink for 64 bit libraries.
13176        if (pkg.applicationInfo.primaryCpuAbi != null &&
13177                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13178            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13179            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13180                    nativeLibPath, userId) < 0) {
13181                Slog.w(TAG, "Failed linking native library dir");
13182                return false;
13183            }
13184        }
13185
13186        return true;
13187    }
13188
13189    /**
13190     * Reverts user permission state changes (permissions and flags).
13191     *
13192     * @param ps The package for which to reset.
13193     * @param userId The device user for which to do a reset.
13194     */
13195    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13196            final PackageSetting ps, final int userId) {
13197        if (ps.pkg == null) {
13198            return;
13199        }
13200
13201        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13202                | FLAG_PERMISSION_USER_FIXED
13203                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13204
13205        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13206                | FLAG_PERMISSION_POLICY_FIXED;
13207
13208        boolean writeInstallPermissions = false;
13209        boolean writeRuntimePermissions = false;
13210
13211        final int permissionCount = ps.pkg.requestedPermissions.size();
13212        for (int i = 0; i < permissionCount; i++) {
13213            String permission = ps.pkg.requestedPermissions.get(i);
13214
13215            BasePermission bp = mSettings.mPermissions.get(permission);
13216            if (bp == null) {
13217                continue;
13218            }
13219
13220            // If shared user we just reset the state to which only this app contributed.
13221            if (ps.sharedUser != null) {
13222                boolean used = false;
13223                final int packageCount = ps.sharedUser.packages.size();
13224                for (int j = 0; j < packageCount; j++) {
13225                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13226                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13227                            && pkg.pkg.requestedPermissions.contains(permission)) {
13228                        used = true;
13229                        break;
13230                    }
13231                }
13232                if (used) {
13233                    continue;
13234                }
13235            }
13236
13237            PermissionsState permissionsState = ps.getPermissionsState();
13238
13239            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13240
13241            // Always clear the user settable flags.
13242            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13243                    bp.name) != null;
13244            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13245                if (hasInstallState) {
13246                    writeInstallPermissions = true;
13247                } else {
13248                    writeRuntimePermissions = true;
13249                }
13250            }
13251
13252            // Below is only runtime permission handling.
13253            if (!bp.isRuntime()) {
13254                continue;
13255            }
13256
13257            // Never clobber system or policy.
13258            if ((oldFlags & policyOrSystemFlags) != 0) {
13259                continue;
13260            }
13261
13262            // If this permission was granted by default, make sure it is.
13263            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13264                if (permissionsState.grantRuntimePermission(bp, userId)
13265                        != PERMISSION_OPERATION_FAILURE) {
13266                    writeRuntimePermissions = true;
13267                }
13268            } else {
13269                // Otherwise, reset the permission.
13270                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13271                switch (revokeResult) {
13272                    case PERMISSION_OPERATION_SUCCESS: {
13273                        writeRuntimePermissions = true;
13274                    } break;
13275
13276                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13277                        writeRuntimePermissions = true;
13278                        // If gids changed for this user, kill all affected packages.
13279                        mHandler.post(new Runnable() {
13280                            @Override
13281                            public void run() {
13282                                // This has to happen with no lock held.
13283                                killSettingPackagesForUser(ps, userId,
13284                                        KILL_APP_REASON_GIDS_CHANGED);
13285                            }
13286                        });
13287                    } break;
13288                }
13289            }
13290        }
13291
13292        // Synchronously write as we are taking permissions away.
13293        if (writeRuntimePermissions) {
13294            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13295        }
13296
13297        // Synchronously write as we are taking permissions away.
13298        if (writeInstallPermissions) {
13299            mSettings.writeLPr();
13300        }
13301    }
13302
13303    /**
13304     * Remove entries from the keystore daemon. Will only remove it if the
13305     * {@code appId} is valid.
13306     */
13307    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13308        if (appId < 0) {
13309            return;
13310        }
13311
13312        final KeyStore keyStore = KeyStore.getInstance();
13313        if (keyStore != null) {
13314            if (userId == UserHandle.USER_ALL) {
13315                for (final int individual : sUserManager.getUserIds()) {
13316                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13317                }
13318            } else {
13319                keyStore.clearUid(UserHandle.getUid(userId, appId));
13320            }
13321        } else {
13322            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13323        }
13324    }
13325
13326    @Override
13327    public void deleteApplicationCacheFiles(final String packageName,
13328            final IPackageDataObserver observer) {
13329        mContext.enforceCallingOrSelfPermission(
13330                android.Manifest.permission.DELETE_CACHE_FILES, null);
13331        // Queue up an async operation since the package deletion may take a little while.
13332        final int userId = UserHandle.getCallingUserId();
13333        mHandler.post(new Runnable() {
13334            public void run() {
13335                mHandler.removeCallbacks(this);
13336                final boolean succeded;
13337                synchronized (mInstallLock) {
13338                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13339                }
13340                clearExternalStorageDataSync(packageName, userId, false);
13341                if (observer != null) {
13342                    try {
13343                        observer.onRemoveCompleted(packageName, succeded);
13344                    } catch (RemoteException e) {
13345                        Log.i(TAG, "Observer no longer exists.");
13346                    }
13347                } //end if observer
13348            } //end run
13349        });
13350    }
13351
13352    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13353        if (packageName == null) {
13354            Slog.w(TAG, "Attempt to delete null packageName.");
13355            return false;
13356        }
13357        PackageParser.Package p;
13358        synchronized (mPackages) {
13359            p = mPackages.get(packageName);
13360        }
13361        if (p == null) {
13362            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13363            return false;
13364        }
13365        final ApplicationInfo applicationInfo = p.applicationInfo;
13366        if (applicationInfo == null) {
13367            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13368            return false;
13369        }
13370        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13371        if (retCode < 0) {
13372            Slog.w(TAG, "Couldn't remove cache files for package: "
13373                       + packageName + " u" + userId);
13374            return false;
13375        }
13376        return true;
13377    }
13378
13379    @Override
13380    public void getPackageSizeInfo(final String packageName, int userHandle,
13381            final IPackageStatsObserver observer) {
13382        mContext.enforceCallingOrSelfPermission(
13383                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13384        if (packageName == null) {
13385            throw new IllegalArgumentException("Attempt to get size of null packageName");
13386        }
13387
13388        PackageStats stats = new PackageStats(packageName, userHandle);
13389
13390        /*
13391         * Queue up an async operation since the package measurement may take a
13392         * little while.
13393         */
13394        Message msg = mHandler.obtainMessage(INIT_COPY);
13395        msg.obj = new MeasureParams(stats, observer);
13396        mHandler.sendMessage(msg);
13397    }
13398
13399    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13400            PackageStats pStats) {
13401        if (packageName == null) {
13402            Slog.w(TAG, "Attempt to get size of null packageName.");
13403            return false;
13404        }
13405        PackageParser.Package p;
13406        boolean dataOnly = false;
13407        String libDirRoot = null;
13408        String asecPath = null;
13409        PackageSetting ps = null;
13410        synchronized (mPackages) {
13411            p = mPackages.get(packageName);
13412            ps = mSettings.mPackages.get(packageName);
13413            if(p == null) {
13414                dataOnly = true;
13415                if((ps == null) || (ps.pkg == null)) {
13416                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13417                    return false;
13418                }
13419                p = ps.pkg;
13420            }
13421            if (ps != null) {
13422                libDirRoot = ps.legacyNativeLibraryPathString;
13423            }
13424            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13425                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13426                if (secureContainerId != null) {
13427                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13428                }
13429            }
13430        }
13431        String publicSrcDir = null;
13432        if(!dataOnly) {
13433            final ApplicationInfo applicationInfo = p.applicationInfo;
13434            if (applicationInfo == null) {
13435                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13436                return false;
13437            }
13438            if (p.isForwardLocked()) {
13439                publicSrcDir = applicationInfo.getBaseResourcePath();
13440            }
13441        }
13442        // TODO: extend to measure size of split APKs
13443        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13444        // not just the first level.
13445        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13446        // just the primary.
13447        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13448        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13449                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13450        if (res < 0) {
13451            return false;
13452        }
13453
13454        // Fix-up for forward-locked applications in ASEC containers.
13455        if (!isExternal(p)) {
13456            pStats.codeSize += pStats.externalCodeSize;
13457            pStats.externalCodeSize = 0L;
13458        }
13459
13460        return true;
13461    }
13462
13463
13464    @Override
13465    public void addPackageToPreferred(String packageName) {
13466        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13467    }
13468
13469    @Override
13470    public void removePackageFromPreferred(String packageName) {
13471        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13472    }
13473
13474    @Override
13475    public List<PackageInfo> getPreferredPackages(int flags) {
13476        return new ArrayList<PackageInfo>();
13477    }
13478
13479    private int getUidTargetSdkVersionLockedLPr(int uid) {
13480        Object obj = mSettings.getUserIdLPr(uid);
13481        if (obj instanceof SharedUserSetting) {
13482            final SharedUserSetting sus = (SharedUserSetting) obj;
13483            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13484            final Iterator<PackageSetting> it = sus.packages.iterator();
13485            while (it.hasNext()) {
13486                final PackageSetting ps = it.next();
13487                if (ps.pkg != null) {
13488                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13489                    if (v < vers) vers = v;
13490                }
13491            }
13492            return vers;
13493        } else if (obj instanceof PackageSetting) {
13494            final PackageSetting ps = (PackageSetting) obj;
13495            if (ps.pkg != null) {
13496                return ps.pkg.applicationInfo.targetSdkVersion;
13497            }
13498        }
13499        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13500    }
13501
13502    @Override
13503    public void addPreferredActivity(IntentFilter filter, int match,
13504            ComponentName[] set, ComponentName activity, int userId) {
13505        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13506                "Adding preferred");
13507    }
13508
13509    private void addPreferredActivityInternal(IntentFilter filter, int match,
13510            ComponentName[] set, ComponentName activity, boolean always, int userId,
13511            String opname) {
13512        // writer
13513        int callingUid = Binder.getCallingUid();
13514        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13515        if (filter.countActions() == 0) {
13516            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13517            return;
13518        }
13519        synchronized (mPackages) {
13520            if (mContext.checkCallingOrSelfPermission(
13521                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13522                    != PackageManager.PERMISSION_GRANTED) {
13523                if (getUidTargetSdkVersionLockedLPr(callingUid)
13524                        < Build.VERSION_CODES.FROYO) {
13525                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13526                            + callingUid);
13527                    return;
13528                }
13529                mContext.enforceCallingOrSelfPermission(
13530                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13531            }
13532
13533            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13534            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13535                    + userId + ":");
13536            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13537            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13538            scheduleWritePackageRestrictionsLocked(userId);
13539        }
13540    }
13541
13542    @Override
13543    public void replacePreferredActivity(IntentFilter filter, int match,
13544            ComponentName[] set, ComponentName activity, int userId) {
13545        if (filter.countActions() != 1) {
13546            throw new IllegalArgumentException(
13547                    "replacePreferredActivity expects filter to have only 1 action.");
13548        }
13549        if (filter.countDataAuthorities() != 0
13550                || filter.countDataPaths() != 0
13551                || filter.countDataSchemes() > 1
13552                || filter.countDataTypes() != 0) {
13553            throw new IllegalArgumentException(
13554                    "replacePreferredActivity expects filter to have no data authorities, " +
13555                    "paths, or types; and at most one scheme.");
13556        }
13557
13558        final int callingUid = Binder.getCallingUid();
13559        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13560        synchronized (mPackages) {
13561            if (mContext.checkCallingOrSelfPermission(
13562                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13563                    != PackageManager.PERMISSION_GRANTED) {
13564                if (getUidTargetSdkVersionLockedLPr(callingUid)
13565                        < Build.VERSION_CODES.FROYO) {
13566                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13567                            + Binder.getCallingUid());
13568                    return;
13569                }
13570                mContext.enforceCallingOrSelfPermission(
13571                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13572            }
13573
13574            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13575            if (pir != null) {
13576                // Get all of the existing entries that exactly match this filter.
13577                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13578                if (existing != null && existing.size() == 1) {
13579                    PreferredActivity cur = existing.get(0);
13580                    if (DEBUG_PREFERRED) {
13581                        Slog.i(TAG, "Checking replace of preferred:");
13582                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13583                        if (!cur.mPref.mAlways) {
13584                            Slog.i(TAG, "  -- CUR; not mAlways!");
13585                        } else {
13586                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13587                            Slog.i(TAG, "  -- CUR: mSet="
13588                                    + Arrays.toString(cur.mPref.mSetComponents));
13589                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13590                            Slog.i(TAG, "  -- NEW: mMatch="
13591                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13592                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13593                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13594                        }
13595                    }
13596                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13597                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13598                            && cur.mPref.sameSet(set)) {
13599                        // Setting the preferred activity to what it happens to be already
13600                        if (DEBUG_PREFERRED) {
13601                            Slog.i(TAG, "Replacing with same preferred activity "
13602                                    + cur.mPref.mShortComponent + " for user "
13603                                    + userId + ":");
13604                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13605                        }
13606                        return;
13607                    }
13608                }
13609
13610                if (existing != null) {
13611                    if (DEBUG_PREFERRED) {
13612                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13613                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13614                    }
13615                    for (int i = 0; i < existing.size(); i++) {
13616                        PreferredActivity pa = existing.get(i);
13617                        if (DEBUG_PREFERRED) {
13618                            Slog.i(TAG, "Removing existing preferred activity "
13619                                    + pa.mPref.mComponent + ":");
13620                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13621                        }
13622                        pir.removeFilter(pa);
13623                    }
13624                }
13625            }
13626            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13627                    "Replacing preferred");
13628        }
13629    }
13630
13631    @Override
13632    public void clearPackagePreferredActivities(String packageName) {
13633        final int uid = Binder.getCallingUid();
13634        // writer
13635        synchronized (mPackages) {
13636            PackageParser.Package pkg = mPackages.get(packageName);
13637            if (pkg == null || pkg.applicationInfo.uid != uid) {
13638                if (mContext.checkCallingOrSelfPermission(
13639                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13640                        != PackageManager.PERMISSION_GRANTED) {
13641                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13642                            < Build.VERSION_CODES.FROYO) {
13643                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13644                                + Binder.getCallingUid());
13645                        return;
13646                    }
13647                    mContext.enforceCallingOrSelfPermission(
13648                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13649                }
13650            }
13651
13652            int user = UserHandle.getCallingUserId();
13653            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13654                scheduleWritePackageRestrictionsLocked(user);
13655            }
13656        }
13657    }
13658
13659    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13660    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13661        ArrayList<PreferredActivity> removed = null;
13662        boolean changed = false;
13663        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13664            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13665            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13666            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13667                continue;
13668            }
13669            Iterator<PreferredActivity> it = pir.filterIterator();
13670            while (it.hasNext()) {
13671                PreferredActivity pa = it.next();
13672                // Mark entry for removal only if it matches the package name
13673                // and the entry is of type "always".
13674                if (packageName == null ||
13675                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13676                                && pa.mPref.mAlways)) {
13677                    if (removed == null) {
13678                        removed = new ArrayList<PreferredActivity>();
13679                    }
13680                    removed.add(pa);
13681                }
13682            }
13683            if (removed != null) {
13684                for (int j=0; j<removed.size(); j++) {
13685                    PreferredActivity pa = removed.get(j);
13686                    pir.removeFilter(pa);
13687                }
13688                changed = true;
13689            }
13690        }
13691        return changed;
13692    }
13693
13694    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13695    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13696        if (userId == UserHandle.USER_ALL) {
13697            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13698                    sUserManager.getUserIds())) {
13699                for (int oneUserId : sUserManager.getUserIds()) {
13700                    scheduleWritePackageRestrictionsLocked(oneUserId);
13701                }
13702            }
13703        } else {
13704            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13705                scheduleWritePackageRestrictionsLocked(userId);
13706            }
13707        }
13708    }
13709
13710
13711    void clearDefaultBrowserIfNeeded(String packageName) {
13712        for (int oneUserId : sUserManager.getUserIds()) {
13713            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13714            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13715            if (packageName.equals(defaultBrowserPackageName)) {
13716                setDefaultBrowserPackageName(null, oneUserId);
13717            }
13718        }
13719    }
13720
13721    @Override
13722    public void resetPreferredActivities(int userId) {
13723        mContext.enforceCallingOrSelfPermission(
13724                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13725        // writer
13726        synchronized (mPackages) {
13727            clearPackagePreferredActivitiesLPw(null, userId);
13728            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13729            applyFactoryDefaultBrowserLPw(userId);
13730            primeDomainVerificationsLPw(userId);
13731
13732            scheduleWritePackageRestrictionsLocked(userId);
13733        }
13734    }
13735
13736    @Override
13737    public int getPreferredActivities(List<IntentFilter> outFilters,
13738            List<ComponentName> outActivities, String packageName) {
13739
13740        int num = 0;
13741        final int userId = UserHandle.getCallingUserId();
13742        // reader
13743        synchronized (mPackages) {
13744            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13745            if (pir != null) {
13746                final Iterator<PreferredActivity> it = pir.filterIterator();
13747                while (it.hasNext()) {
13748                    final PreferredActivity pa = it.next();
13749                    if (packageName == null
13750                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13751                                    && pa.mPref.mAlways)) {
13752                        if (outFilters != null) {
13753                            outFilters.add(new IntentFilter(pa));
13754                        }
13755                        if (outActivities != null) {
13756                            outActivities.add(pa.mPref.mComponent);
13757                        }
13758                    }
13759                }
13760            }
13761        }
13762
13763        return num;
13764    }
13765
13766    @Override
13767    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13768            int userId) {
13769        int callingUid = Binder.getCallingUid();
13770        if (callingUid != Process.SYSTEM_UID) {
13771            throw new SecurityException(
13772                    "addPersistentPreferredActivity can only be run by the system");
13773        }
13774        if (filter.countActions() == 0) {
13775            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13776            return;
13777        }
13778        synchronized (mPackages) {
13779            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13780                    " :");
13781            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13782            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13783                    new PersistentPreferredActivity(filter, activity));
13784            scheduleWritePackageRestrictionsLocked(userId);
13785        }
13786    }
13787
13788    @Override
13789    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13790        int callingUid = Binder.getCallingUid();
13791        if (callingUid != Process.SYSTEM_UID) {
13792            throw new SecurityException(
13793                    "clearPackagePersistentPreferredActivities can only be run by the system");
13794        }
13795        ArrayList<PersistentPreferredActivity> removed = null;
13796        boolean changed = false;
13797        synchronized (mPackages) {
13798            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13799                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13800                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13801                        .valueAt(i);
13802                if (userId != thisUserId) {
13803                    continue;
13804                }
13805                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13806                while (it.hasNext()) {
13807                    PersistentPreferredActivity ppa = it.next();
13808                    // Mark entry for removal only if it matches the package name.
13809                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13810                        if (removed == null) {
13811                            removed = new ArrayList<PersistentPreferredActivity>();
13812                        }
13813                        removed.add(ppa);
13814                    }
13815                }
13816                if (removed != null) {
13817                    for (int j=0; j<removed.size(); j++) {
13818                        PersistentPreferredActivity ppa = removed.get(j);
13819                        ppir.removeFilter(ppa);
13820                    }
13821                    changed = true;
13822                }
13823            }
13824
13825            if (changed) {
13826                scheduleWritePackageRestrictionsLocked(userId);
13827            }
13828        }
13829    }
13830
13831    /**
13832     * Common machinery for picking apart a restored XML blob and passing
13833     * it to a caller-supplied functor to be applied to the running system.
13834     */
13835    private void restoreFromXml(XmlPullParser parser, int userId,
13836            String expectedStartTag, BlobXmlRestorer functor)
13837            throws IOException, XmlPullParserException {
13838        int type;
13839        while ((type = parser.next()) != XmlPullParser.START_TAG
13840                && type != XmlPullParser.END_DOCUMENT) {
13841        }
13842        if (type != XmlPullParser.START_TAG) {
13843            // oops didn't find a start tag?!
13844            if (DEBUG_BACKUP) {
13845                Slog.e(TAG, "Didn't find start tag during restore");
13846            }
13847            return;
13848        }
13849
13850        // this is supposed to be TAG_PREFERRED_BACKUP
13851        if (!expectedStartTag.equals(parser.getName())) {
13852            if (DEBUG_BACKUP) {
13853                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13854            }
13855            return;
13856        }
13857
13858        // skip interfering stuff, then we're aligned with the backing implementation
13859        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13860        functor.apply(parser, userId);
13861    }
13862
13863    private interface BlobXmlRestorer {
13864        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13865    }
13866
13867    /**
13868     * Non-Binder method, support for the backup/restore mechanism: write the
13869     * full set of preferred activities in its canonical XML format.  Returns the
13870     * XML output as a byte array, or null if there is none.
13871     */
13872    @Override
13873    public byte[] getPreferredActivityBackup(int userId) {
13874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13875            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13876        }
13877
13878        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13879        try {
13880            final XmlSerializer serializer = new FastXmlSerializer();
13881            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13882            serializer.startDocument(null, true);
13883            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13884
13885            synchronized (mPackages) {
13886                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13887            }
13888
13889            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13890            serializer.endDocument();
13891            serializer.flush();
13892        } catch (Exception e) {
13893            if (DEBUG_BACKUP) {
13894                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13895            }
13896            return null;
13897        }
13898
13899        return dataStream.toByteArray();
13900    }
13901
13902    @Override
13903    public void restorePreferredActivities(byte[] backup, int userId) {
13904        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13905            throw new SecurityException("Only the system may call restorePreferredActivities()");
13906        }
13907
13908        try {
13909            final XmlPullParser parser = Xml.newPullParser();
13910            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13911            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13912                    new BlobXmlRestorer() {
13913                        @Override
13914                        public void apply(XmlPullParser parser, int userId)
13915                                throws XmlPullParserException, IOException {
13916                            synchronized (mPackages) {
13917                                mSettings.readPreferredActivitiesLPw(parser, userId);
13918                            }
13919                        }
13920                    } );
13921        } catch (Exception e) {
13922            if (DEBUG_BACKUP) {
13923                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13924            }
13925        }
13926    }
13927
13928    /**
13929     * Non-Binder method, support for the backup/restore mechanism: write the
13930     * default browser (etc) settings in its canonical XML format.  Returns the default
13931     * browser XML representation as a byte array, or null if there is none.
13932     */
13933    @Override
13934    public byte[] getDefaultAppsBackup(int userId) {
13935        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13936            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13937        }
13938
13939        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13940        try {
13941            final XmlSerializer serializer = new FastXmlSerializer();
13942            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13943            serializer.startDocument(null, true);
13944            serializer.startTag(null, TAG_DEFAULT_APPS);
13945
13946            synchronized (mPackages) {
13947                mSettings.writeDefaultAppsLPr(serializer, userId);
13948            }
13949
13950            serializer.endTag(null, TAG_DEFAULT_APPS);
13951            serializer.endDocument();
13952            serializer.flush();
13953        } catch (Exception e) {
13954            if (DEBUG_BACKUP) {
13955                Slog.e(TAG, "Unable to write default apps for backup", e);
13956            }
13957            return null;
13958        }
13959
13960        return dataStream.toByteArray();
13961    }
13962
13963    @Override
13964    public void restoreDefaultApps(byte[] backup, int userId) {
13965        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13966            throw new SecurityException("Only the system may call restoreDefaultApps()");
13967        }
13968
13969        try {
13970            final XmlPullParser parser = Xml.newPullParser();
13971            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13972            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13973                    new BlobXmlRestorer() {
13974                        @Override
13975                        public void apply(XmlPullParser parser, int userId)
13976                                throws XmlPullParserException, IOException {
13977                            synchronized (mPackages) {
13978                                mSettings.readDefaultAppsLPw(parser, userId);
13979                            }
13980                        }
13981                    } );
13982        } catch (Exception e) {
13983            if (DEBUG_BACKUP) {
13984                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13985            }
13986        }
13987    }
13988
13989    @Override
13990    public byte[] getIntentFilterVerificationBackup(int userId) {
13991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13992            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13993        }
13994
13995        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13996        try {
13997            final XmlSerializer serializer = new FastXmlSerializer();
13998            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13999            serializer.startDocument(null, true);
14000            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14001
14002            synchronized (mPackages) {
14003                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14004            }
14005
14006            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14007            serializer.endDocument();
14008            serializer.flush();
14009        } catch (Exception e) {
14010            if (DEBUG_BACKUP) {
14011                Slog.e(TAG, "Unable to write default apps for backup", e);
14012            }
14013            return null;
14014        }
14015
14016        return dataStream.toByteArray();
14017    }
14018
14019    @Override
14020    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14021        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14022            throw new SecurityException("Only the system may call restorePreferredActivities()");
14023        }
14024
14025        try {
14026            final XmlPullParser parser = Xml.newPullParser();
14027            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14028            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14029                    new BlobXmlRestorer() {
14030                        @Override
14031                        public void apply(XmlPullParser parser, int userId)
14032                                throws XmlPullParserException, IOException {
14033                            synchronized (mPackages) {
14034                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14035                                mSettings.writeLPr();
14036                            }
14037                        }
14038                    } );
14039        } catch (Exception e) {
14040            if (DEBUG_BACKUP) {
14041                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14042            }
14043        }
14044    }
14045
14046    @Override
14047    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14048            int sourceUserId, int targetUserId, int flags) {
14049        mContext.enforceCallingOrSelfPermission(
14050                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14051        int callingUid = Binder.getCallingUid();
14052        enforceOwnerRights(ownerPackage, callingUid);
14053        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14054        if (intentFilter.countActions() == 0) {
14055            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14056            return;
14057        }
14058        synchronized (mPackages) {
14059            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14060                    ownerPackage, targetUserId, flags);
14061            CrossProfileIntentResolver resolver =
14062                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14063            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14064            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14065            if (existing != null) {
14066                int size = existing.size();
14067                for (int i = 0; i < size; i++) {
14068                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14069                        return;
14070                    }
14071                }
14072            }
14073            resolver.addFilter(newFilter);
14074            scheduleWritePackageRestrictionsLocked(sourceUserId);
14075        }
14076    }
14077
14078    @Override
14079    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14080        mContext.enforceCallingOrSelfPermission(
14081                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14082        int callingUid = Binder.getCallingUid();
14083        enforceOwnerRights(ownerPackage, callingUid);
14084        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14085        synchronized (mPackages) {
14086            CrossProfileIntentResolver resolver =
14087                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14088            ArraySet<CrossProfileIntentFilter> set =
14089                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14090            for (CrossProfileIntentFilter filter : set) {
14091                if (filter.getOwnerPackage().equals(ownerPackage)) {
14092                    resolver.removeFilter(filter);
14093                }
14094            }
14095            scheduleWritePackageRestrictionsLocked(sourceUserId);
14096        }
14097    }
14098
14099    // Enforcing that callingUid is owning pkg on userId
14100    private void enforceOwnerRights(String pkg, int callingUid) {
14101        // The system owns everything.
14102        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14103            return;
14104        }
14105        int callingUserId = UserHandle.getUserId(callingUid);
14106        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14107        if (pi == null) {
14108            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14109                    + callingUserId);
14110        }
14111        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14112            throw new SecurityException("Calling uid " + callingUid
14113                    + " does not own package " + pkg);
14114        }
14115    }
14116
14117    @Override
14118    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14119        Intent intent = new Intent(Intent.ACTION_MAIN);
14120        intent.addCategory(Intent.CATEGORY_HOME);
14121
14122        final int callingUserId = UserHandle.getCallingUserId();
14123        List<ResolveInfo> list = queryIntentActivities(intent, null,
14124                PackageManager.GET_META_DATA, callingUserId);
14125        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14126                true, false, false, callingUserId);
14127
14128        allHomeCandidates.clear();
14129        if (list != null) {
14130            for (ResolveInfo ri : list) {
14131                allHomeCandidates.add(ri);
14132            }
14133        }
14134        return (preferred == null || preferred.activityInfo == null)
14135                ? null
14136                : new ComponentName(preferred.activityInfo.packageName,
14137                        preferred.activityInfo.name);
14138    }
14139
14140    @Override
14141    public void setApplicationEnabledSetting(String appPackageName,
14142            int newState, int flags, int userId, String callingPackage) {
14143        if (!sUserManager.exists(userId)) return;
14144        if (callingPackage == null) {
14145            callingPackage = Integer.toString(Binder.getCallingUid());
14146        }
14147        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14148    }
14149
14150    @Override
14151    public void setComponentEnabledSetting(ComponentName componentName,
14152            int newState, int flags, int userId) {
14153        if (!sUserManager.exists(userId)) return;
14154        setEnabledSetting(componentName.getPackageName(),
14155                componentName.getClassName(), newState, flags, userId, null);
14156    }
14157
14158    private void setEnabledSetting(final String packageName, String className, int newState,
14159            final int flags, int userId, String callingPackage) {
14160        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14161              || newState == COMPONENT_ENABLED_STATE_ENABLED
14162              || newState == COMPONENT_ENABLED_STATE_DISABLED
14163              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14164              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14165            throw new IllegalArgumentException("Invalid new component state: "
14166                    + newState);
14167        }
14168        PackageSetting pkgSetting;
14169        final int uid = Binder.getCallingUid();
14170        final int permission = mContext.checkCallingOrSelfPermission(
14171                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14172        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14173        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14174        boolean sendNow = false;
14175        boolean isApp = (className == null);
14176        String componentName = isApp ? packageName : className;
14177        int packageUid = -1;
14178        ArrayList<String> components;
14179
14180        // writer
14181        synchronized (mPackages) {
14182            pkgSetting = mSettings.mPackages.get(packageName);
14183            if (pkgSetting == null) {
14184                if (className == null) {
14185                    throw new IllegalArgumentException(
14186                            "Unknown package: " + packageName);
14187                }
14188                throw new IllegalArgumentException(
14189                        "Unknown component: " + packageName
14190                        + "/" + className);
14191            }
14192            // Allow root and verify that userId is not being specified by a different user
14193            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14194                throw new SecurityException(
14195                        "Permission Denial: attempt to change component state from pid="
14196                        + Binder.getCallingPid()
14197                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14198            }
14199            if (className == null) {
14200                // We're dealing with an application/package level state change
14201                if (pkgSetting.getEnabled(userId) == newState) {
14202                    // Nothing to do
14203                    return;
14204                }
14205                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14206                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14207                    // Don't care about who enables an app.
14208                    callingPackage = null;
14209                }
14210                pkgSetting.setEnabled(newState, userId, callingPackage);
14211                // pkgSetting.pkg.mSetEnabled = newState;
14212            } else {
14213                // We're dealing with a component level state change
14214                // First, verify that this is a valid class name.
14215                PackageParser.Package pkg = pkgSetting.pkg;
14216                if (pkg == null || !pkg.hasComponentClassName(className)) {
14217                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14218                        throw new IllegalArgumentException("Component class " + className
14219                                + " does not exist in " + packageName);
14220                    } else {
14221                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14222                                + className + " does not exist in " + packageName);
14223                    }
14224                }
14225                switch (newState) {
14226                case COMPONENT_ENABLED_STATE_ENABLED:
14227                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14228                        return;
14229                    }
14230                    break;
14231                case COMPONENT_ENABLED_STATE_DISABLED:
14232                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14233                        return;
14234                    }
14235                    break;
14236                case COMPONENT_ENABLED_STATE_DEFAULT:
14237                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14238                        return;
14239                    }
14240                    break;
14241                default:
14242                    Slog.e(TAG, "Invalid new component state: " + newState);
14243                    return;
14244                }
14245            }
14246            scheduleWritePackageRestrictionsLocked(userId);
14247            components = mPendingBroadcasts.get(userId, packageName);
14248            final boolean newPackage = components == null;
14249            if (newPackage) {
14250                components = new ArrayList<String>();
14251            }
14252            if (!components.contains(componentName)) {
14253                components.add(componentName);
14254            }
14255            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14256                sendNow = true;
14257                // Purge entry from pending broadcast list if another one exists already
14258                // since we are sending one right away.
14259                mPendingBroadcasts.remove(userId, packageName);
14260            } else {
14261                if (newPackage) {
14262                    mPendingBroadcasts.put(userId, packageName, components);
14263                }
14264                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14265                    // Schedule a message
14266                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14267                }
14268            }
14269        }
14270
14271        long callingId = Binder.clearCallingIdentity();
14272        try {
14273            if (sendNow) {
14274                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14275                sendPackageChangedBroadcast(packageName,
14276                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14277            }
14278        } finally {
14279            Binder.restoreCallingIdentity(callingId);
14280        }
14281    }
14282
14283    private void sendPackageChangedBroadcast(String packageName,
14284            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14285        if (DEBUG_INSTALL)
14286            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14287                    + componentNames);
14288        Bundle extras = new Bundle(4);
14289        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14290        String nameList[] = new String[componentNames.size()];
14291        componentNames.toArray(nameList);
14292        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14293        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14294        extras.putInt(Intent.EXTRA_UID, packageUid);
14295        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14296                new int[] {UserHandle.getUserId(packageUid)});
14297    }
14298
14299    @Override
14300    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14301        if (!sUserManager.exists(userId)) return;
14302        final int uid = Binder.getCallingUid();
14303        final int permission = mContext.checkCallingOrSelfPermission(
14304                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14305        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14306        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14307        // writer
14308        synchronized (mPackages) {
14309            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14310                    allowedByPermission, uid, userId)) {
14311                scheduleWritePackageRestrictionsLocked(userId);
14312            }
14313        }
14314    }
14315
14316    @Override
14317    public String getInstallerPackageName(String packageName) {
14318        // reader
14319        synchronized (mPackages) {
14320            return mSettings.getInstallerPackageNameLPr(packageName);
14321        }
14322    }
14323
14324    @Override
14325    public int getApplicationEnabledSetting(String packageName, int userId) {
14326        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14327        int uid = Binder.getCallingUid();
14328        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14329        // reader
14330        synchronized (mPackages) {
14331            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14332        }
14333    }
14334
14335    @Override
14336    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14337        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14338        int uid = Binder.getCallingUid();
14339        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14340        // reader
14341        synchronized (mPackages) {
14342            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14343        }
14344    }
14345
14346    @Override
14347    public void enterSafeMode() {
14348        enforceSystemOrRoot("Only the system can request entering safe mode");
14349
14350        if (!mSystemReady) {
14351            mSafeMode = true;
14352        }
14353    }
14354
14355    @Override
14356    public void systemReady() {
14357        mSystemReady = true;
14358
14359        // Read the compatibilty setting when the system is ready.
14360        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14361                mContext.getContentResolver(),
14362                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14363        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14364        if (DEBUG_SETTINGS) {
14365            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14366        }
14367
14368        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14369
14370        synchronized (mPackages) {
14371            // Verify that all of the preferred activity components actually
14372            // exist.  It is possible for applications to be updated and at
14373            // that point remove a previously declared activity component that
14374            // had been set as a preferred activity.  We try to clean this up
14375            // the next time we encounter that preferred activity, but it is
14376            // possible for the user flow to never be able to return to that
14377            // situation so here we do a sanity check to make sure we haven't
14378            // left any junk around.
14379            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14380            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14381                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14382                removed.clear();
14383                for (PreferredActivity pa : pir.filterSet()) {
14384                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14385                        removed.add(pa);
14386                    }
14387                }
14388                if (removed.size() > 0) {
14389                    for (int r=0; r<removed.size(); r++) {
14390                        PreferredActivity pa = removed.get(r);
14391                        Slog.w(TAG, "Removing dangling preferred activity: "
14392                                + pa.mPref.mComponent);
14393                        pir.removeFilter(pa);
14394                    }
14395                    mSettings.writePackageRestrictionsLPr(
14396                            mSettings.mPreferredActivities.keyAt(i));
14397                }
14398            }
14399
14400            for (int userId : UserManagerService.getInstance().getUserIds()) {
14401                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14402                    grantPermissionsUserIds = ArrayUtils.appendInt(
14403                            grantPermissionsUserIds, userId);
14404                }
14405            }
14406        }
14407        sUserManager.systemReady();
14408
14409        // If we upgraded grant all default permissions before kicking off.
14410        for (int userId : grantPermissionsUserIds) {
14411            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14412        }
14413
14414        // Kick off any messages waiting for system ready
14415        if (mPostSystemReadyMessages != null) {
14416            for (Message msg : mPostSystemReadyMessages) {
14417                msg.sendToTarget();
14418            }
14419            mPostSystemReadyMessages = null;
14420        }
14421
14422        // Watch for external volumes that come and go over time
14423        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14424        storage.registerListener(mStorageListener);
14425
14426        mInstallerService.systemReady();
14427        mPackageDexOptimizer.systemReady();
14428
14429        MountServiceInternal mountServiceInternal = LocalServices.getService(
14430                MountServiceInternal.class);
14431        mountServiceInternal.addExternalStoragePolicy(
14432                new MountServiceInternal.ExternalStorageMountPolicy() {
14433            @Override
14434            public int getMountMode(int uid, String packageName) {
14435                if (Process.isIsolated(uid)) {
14436                    return Zygote.MOUNT_EXTERNAL_NONE;
14437                }
14438                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14439                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14440                }
14441                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14442                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14443                }
14444                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14445                    return Zygote.MOUNT_EXTERNAL_READ;
14446                }
14447                return Zygote.MOUNT_EXTERNAL_WRITE;
14448            }
14449
14450            @Override
14451            public boolean hasExternalStorage(int uid, String packageName) {
14452                return true;
14453            }
14454        });
14455    }
14456
14457    @Override
14458    public boolean isSafeMode() {
14459        return mSafeMode;
14460    }
14461
14462    @Override
14463    public boolean hasSystemUidErrors() {
14464        return mHasSystemUidErrors;
14465    }
14466
14467    static String arrayToString(int[] array) {
14468        StringBuffer buf = new StringBuffer(128);
14469        buf.append('[');
14470        if (array != null) {
14471            for (int i=0; i<array.length; i++) {
14472                if (i > 0) buf.append(", ");
14473                buf.append(array[i]);
14474            }
14475        }
14476        buf.append(']');
14477        return buf.toString();
14478    }
14479
14480    static class DumpState {
14481        public static final int DUMP_LIBS = 1 << 0;
14482        public static final int DUMP_FEATURES = 1 << 1;
14483        public static final int DUMP_RESOLVERS = 1 << 2;
14484        public static final int DUMP_PERMISSIONS = 1 << 3;
14485        public static final int DUMP_PACKAGES = 1 << 4;
14486        public static final int DUMP_SHARED_USERS = 1 << 5;
14487        public static final int DUMP_MESSAGES = 1 << 6;
14488        public static final int DUMP_PROVIDERS = 1 << 7;
14489        public static final int DUMP_VERIFIERS = 1 << 8;
14490        public static final int DUMP_PREFERRED = 1 << 9;
14491        public static final int DUMP_PREFERRED_XML = 1 << 10;
14492        public static final int DUMP_KEYSETS = 1 << 11;
14493        public static final int DUMP_VERSION = 1 << 12;
14494        public static final int DUMP_INSTALLS = 1 << 13;
14495        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14496        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14497
14498        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14499
14500        private int mTypes;
14501
14502        private int mOptions;
14503
14504        private boolean mTitlePrinted;
14505
14506        private SharedUserSetting mSharedUser;
14507
14508        public boolean isDumping(int type) {
14509            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14510                return true;
14511            }
14512
14513            return (mTypes & type) != 0;
14514        }
14515
14516        public void setDump(int type) {
14517            mTypes |= type;
14518        }
14519
14520        public boolean isOptionEnabled(int option) {
14521            return (mOptions & option) != 0;
14522        }
14523
14524        public void setOptionEnabled(int option) {
14525            mOptions |= option;
14526        }
14527
14528        public boolean onTitlePrinted() {
14529            final boolean printed = mTitlePrinted;
14530            mTitlePrinted = true;
14531            return printed;
14532        }
14533
14534        public boolean getTitlePrinted() {
14535            return mTitlePrinted;
14536        }
14537
14538        public void setTitlePrinted(boolean enabled) {
14539            mTitlePrinted = enabled;
14540        }
14541
14542        public SharedUserSetting getSharedUser() {
14543            return mSharedUser;
14544        }
14545
14546        public void setSharedUser(SharedUserSetting user) {
14547            mSharedUser = user;
14548        }
14549    }
14550
14551    @Override
14552    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14553        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14554                != PackageManager.PERMISSION_GRANTED) {
14555            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14556                    + Binder.getCallingPid()
14557                    + ", uid=" + Binder.getCallingUid()
14558                    + " without permission "
14559                    + android.Manifest.permission.DUMP);
14560            return;
14561        }
14562
14563        DumpState dumpState = new DumpState();
14564        boolean fullPreferred = false;
14565        boolean checkin = false;
14566
14567        String packageName = null;
14568        ArraySet<String> permissionNames = null;
14569
14570        int opti = 0;
14571        while (opti < args.length) {
14572            String opt = args[opti];
14573            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14574                break;
14575            }
14576            opti++;
14577
14578            if ("-a".equals(opt)) {
14579                // Right now we only know how to print all.
14580            } else if ("-h".equals(opt)) {
14581                pw.println("Package manager dump options:");
14582                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14583                pw.println("    --checkin: dump for a checkin");
14584                pw.println("    -f: print details of intent filters");
14585                pw.println("    -h: print this help");
14586                pw.println("  cmd may be one of:");
14587                pw.println("    l[ibraries]: list known shared libraries");
14588                pw.println("    f[ibraries]: list device features");
14589                pw.println("    k[eysets]: print known keysets");
14590                pw.println("    r[esolvers]: dump intent resolvers");
14591                pw.println("    perm[issions]: dump permissions");
14592                pw.println("    permission [name ...]: dump declaration and use of given permission");
14593                pw.println("    pref[erred]: print preferred package settings");
14594                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14595                pw.println("    prov[iders]: dump content providers");
14596                pw.println("    p[ackages]: dump installed packages");
14597                pw.println("    s[hared-users]: dump shared user IDs");
14598                pw.println("    m[essages]: print collected runtime messages");
14599                pw.println("    v[erifiers]: print package verifier info");
14600                pw.println("    version: print database version info");
14601                pw.println("    write: write current settings now");
14602                pw.println("    <package.name>: info about given package");
14603                pw.println("    installs: details about install sessions");
14604                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14605                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14606                return;
14607            } else if ("--checkin".equals(opt)) {
14608                checkin = true;
14609            } else if ("-f".equals(opt)) {
14610                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14611            } else {
14612                pw.println("Unknown argument: " + opt + "; use -h for help");
14613            }
14614        }
14615
14616        // Is the caller requesting to dump a particular piece of data?
14617        if (opti < args.length) {
14618            String cmd = args[opti];
14619            opti++;
14620            // Is this a package name?
14621            if ("android".equals(cmd) || cmd.contains(".")) {
14622                packageName = cmd;
14623                // When dumping a single package, we always dump all of its
14624                // filter information since the amount of data will be reasonable.
14625                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14626            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14627                dumpState.setDump(DumpState.DUMP_LIBS);
14628            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14629                dumpState.setDump(DumpState.DUMP_FEATURES);
14630            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14631                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14632            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14633                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14634            } else if ("permission".equals(cmd)) {
14635                if (opti >= args.length) {
14636                    pw.println("Error: permission requires permission name");
14637                    return;
14638                }
14639                permissionNames = new ArraySet<>();
14640                while (opti < args.length) {
14641                    permissionNames.add(args[opti]);
14642                    opti++;
14643                }
14644                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14645                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14646            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14647                dumpState.setDump(DumpState.DUMP_PREFERRED);
14648            } else if ("preferred-xml".equals(cmd)) {
14649                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14650                if (opti < args.length && "--full".equals(args[opti])) {
14651                    fullPreferred = true;
14652                    opti++;
14653                }
14654            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14655                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14656            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14657                dumpState.setDump(DumpState.DUMP_PACKAGES);
14658            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14659                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14660            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14661                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14662            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14663                dumpState.setDump(DumpState.DUMP_MESSAGES);
14664            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14665                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14666            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14667                    || "intent-filter-verifiers".equals(cmd)) {
14668                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14669            } else if ("version".equals(cmd)) {
14670                dumpState.setDump(DumpState.DUMP_VERSION);
14671            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14672                dumpState.setDump(DumpState.DUMP_KEYSETS);
14673            } else if ("installs".equals(cmd)) {
14674                dumpState.setDump(DumpState.DUMP_INSTALLS);
14675            } else if ("write".equals(cmd)) {
14676                synchronized (mPackages) {
14677                    mSettings.writeLPr();
14678                    pw.println("Settings written.");
14679                    return;
14680                }
14681            }
14682        }
14683
14684        if (checkin) {
14685            pw.println("vers,1");
14686        }
14687
14688        // reader
14689        synchronized (mPackages) {
14690            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14691                if (!checkin) {
14692                    if (dumpState.onTitlePrinted())
14693                        pw.println();
14694                    pw.println("Database versions:");
14695                    pw.print("  SDK Version:");
14696                    pw.print(" internal=");
14697                    pw.print(mSettings.mInternalSdkPlatform);
14698                    pw.print(" external=");
14699                    pw.println(mSettings.mExternalSdkPlatform);
14700                    pw.print("  DB Version:");
14701                    pw.print(" internal=");
14702                    pw.print(mSettings.mInternalDatabaseVersion);
14703                    pw.print(" external=");
14704                    pw.println(mSettings.mExternalDatabaseVersion);
14705                }
14706            }
14707
14708            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14709                if (!checkin) {
14710                    if (dumpState.onTitlePrinted())
14711                        pw.println();
14712                    pw.println("Verifiers:");
14713                    pw.print("  Required: ");
14714                    pw.print(mRequiredVerifierPackage);
14715                    pw.print(" (uid=");
14716                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14717                    pw.println(")");
14718                } else if (mRequiredVerifierPackage != null) {
14719                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14720                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14721                }
14722            }
14723
14724            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14725                    packageName == null) {
14726                if (mIntentFilterVerifierComponent != null) {
14727                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14728                    if (!checkin) {
14729                        if (dumpState.onTitlePrinted())
14730                            pw.println();
14731                        pw.println("Intent Filter Verifier:");
14732                        pw.print("  Using: ");
14733                        pw.print(verifierPackageName);
14734                        pw.print(" (uid=");
14735                        pw.print(getPackageUid(verifierPackageName, 0));
14736                        pw.println(")");
14737                    } else if (verifierPackageName != null) {
14738                        pw.print("ifv,"); pw.print(verifierPackageName);
14739                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14740                    }
14741                } else {
14742                    pw.println();
14743                    pw.println("No Intent Filter Verifier available!");
14744                }
14745            }
14746
14747            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14748                boolean printedHeader = false;
14749                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14750                while (it.hasNext()) {
14751                    String name = it.next();
14752                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14753                    if (!checkin) {
14754                        if (!printedHeader) {
14755                            if (dumpState.onTitlePrinted())
14756                                pw.println();
14757                            pw.println("Libraries:");
14758                            printedHeader = true;
14759                        }
14760                        pw.print("  ");
14761                    } else {
14762                        pw.print("lib,");
14763                    }
14764                    pw.print(name);
14765                    if (!checkin) {
14766                        pw.print(" -> ");
14767                    }
14768                    if (ent.path != null) {
14769                        if (!checkin) {
14770                            pw.print("(jar) ");
14771                            pw.print(ent.path);
14772                        } else {
14773                            pw.print(",jar,");
14774                            pw.print(ent.path);
14775                        }
14776                    } else {
14777                        if (!checkin) {
14778                            pw.print("(apk) ");
14779                            pw.print(ent.apk);
14780                        } else {
14781                            pw.print(",apk,");
14782                            pw.print(ent.apk);
14783                        }
14784                    }
14785                    pw.println();
14786                }
14787            }
14788
14789            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14790                if (dumpState.onTitlePrinted())
14791                    pw.println();
14792                if (!checkin) {
14793                    pw.println("Features:");
14794                }
14795                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14796                while (it.hasNext()) {
14797                    String name = it.next();
14798                    if (!checkin) {
14799                        pw.print("  ");
14800                    } else {
14801                        pw.print("feat,");
14802                    }
14803                    pw.println(name);
14804                }
14805            }
14806
14807            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14808                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14809                        : "Activity Resolver Table:", "  ", packageName,
14810                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14811                    dumpState.setTitlePrinted(true);
14812                }
14813                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14814                        : "Receiver Resolver Table:", "  ", packageName,
14815                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14816                    dumpState.setTitlePrinted(true);
14817                }
14818                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14819                        : "Service Resolver Table:", "  ", packageName,
14820                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14821                    dumpState.setTitlePrinted(true);
14822                }
14823                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14824                        : "Provider Resolver Table:", "  ", packageName,
14825                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14826                    dumpState.setTitlePrinted(true);
14827                }
14828            }
14829
14830            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14831                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14832                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14833                    int user = mSettings.mPreferredActivities.keyAt(i);
14834                    if (pir.dump(pw,
14835                            dumpState.getTitlePrinted()
14836                                ? "\nPreferred Activities User " + user + ":"
14837                                : "Preferred Activities User " + user + ":", "  ",
14838                            packageName, true, false)) {
14839                        dumpState.setTitlePrinted(true);
14840                    }
14841                }
14842            }
14843
14844            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14845                pw.flush();
14846                FileOutputStream fout = new FileOutputStream(fd);
14847                BufferedOutputStream str = new BufferedOutputStream(fout);
14848                XmlSerializer serializer = new FastXmlSerializer();
14849                try {
14850                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14851                    serializer.startDocument(null, true);
14852                    serializer.setFeature(
14853                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14854                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14855                    serializer.endDocument();
14856                    serializer.flush();
14857                } catch (IllegalArgumentException e) {
14858                    pw.println("Failed writing: " + e);
14859                } catch (IllegalStateException e) {
14860                    pw.println("Failed writing: " + e);
14861                } catch (IOException e) {
14862                    pw.println("Failed writing: " + e);
14863                }
14864            }
14865
14866            if (!checkin
14867                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14868                    && packageName == null) {
14869                pw.println();
14870                int count = mSettings.mPackages.size();
14871                if (count == 0) {
14872                    pw.println("No applications!");
14873                    pw.println();
14874                } else {
14875                    final String prefix = "  ";
14876                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14877                    if (allPackageSettings.size() == 0) {
14878                        pw.println("No domain preferred apps!");
14879                        pw.println();
14880                    } else {
14881                        pw.println("App verification status:");
14882                        pw.println();
14883                        count = 0;
14884                        for (PackageSetting ps : allPackageSettings) {
14885                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14886                            if (ivi == null || ivi.getPackageName() == null) continue;
14887                            pw.println(prefix + "Package: " + ivi.getPackageName());
14888                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14889                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14890                            pw.println();
14891                            count++;
14892                        }
14893                        if (count == 0) {
14894                            pw.println(prefix + "No app verification established.");
14895                            pw.println();
14896                        }
14897                        for (int userId : sUserManager.getUserIds()) {
14898                            pw.println("App linkages for user " + userId + ":");
14899                            pw.println();
14900                            count = 0;
14901                            for (PackageSetting ps : allPackageSettings) {
14902                                final int status = ps.getDomainVerificationStatusForUser(userId);
14903                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14904                                    continue;
14905                                }
14906                                pw.println(prefix + "Package: " + ps.name);
14907                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14908                                String statusStr = IntentFilterVerificationInfo.
14909                                        getStatusStringFromValue(status);
14910                                pw.println(prefix + "Status:  " + statusStr);
14911                                pw.println();
14912                                count++;
14913                            }
14914                            if (count == 0) {
14915                                pw.println(prefix + "No configured app linkages.");
14916                                pw.println();
14917                            }
14918                        }
14919                    }
14920                }
14921            }
14922
14923            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14924                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14925                if (packageName == null && permissionNames == null) {
14926                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14927                        if (iperm == 0) {
14928                            if (dumpState.onTitlePrinted())
14929                                pw.println();
14930                            pw.println("AppOp Permissions:");
14931                        }
14932                        pw.print("  AppOp Permission ");
14933                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14934                        pw.println(":");
14935                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14936                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14937                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14938                        }
14939                    }
14940                }
14941            }
14942
14943            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14944                boolean printedSomething = false;
14945                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14946                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14947                        continue;
14948                    }
14949                    if (!printedSomething) {
14950                        if (dumpState.onTitlePrinted())
14951                            pw.println();
14952                        pw.println("Registered ContentProviders:");
14953                        printedSomething = true;
14954                    }
14955                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14956                    pw.print("    "); pw.println(p.toString());
14957                }
14958                printedSomething = false;
14959                for (Map.Entry<String, PackageParser.Provider> entry :
14960                        mProvidersByAuthority.entrySet()) {
14961                    PackageParser.Provider p = entry.getValue();
14962                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14963                        continue;
14964                    }
14965                    if (!printedSomething) {
14966                        if (dumpState.onTitlePrinted())
14967                            pw.println();
14968                        pw.println("ContentProvider Authorities:");
14969                        printedSomething = true;
14970                    }
14971                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14972                    pw.print("    "); pw.println(p.toString());
14973                    if (p.info != null && p.info.applicationInfo != null) {
14974                        final String appInfo = p.info.applicationInfo.toString();
14975                        pw.print("      applicationInfo="); pw.println(appInfo);
14976                    }
14977                }
14978            }
14979
14980            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14981                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14982            }
14983
14984            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14985                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14986            }
14987
14988            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14989                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14990            }
14991
14992            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14993                // XXX should handle packageName != null by dumping only install data that
14994                // the given package is involved with.
14995                if (dumpState.onTitlePrinted()) pw.println();
14996                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14997            }
14998
14999            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15000                if (dumpState.onTitlePrinted()) pw.println();
15001                mSettings.dumpReadMessagesLPr(pw, dumpState);
15002
15003                pw.println();
15004                pw.println("Package warning messages:");
15005                BufferedReader in = null;
15006                String line = null;
15007                try {
15008                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15009                    while ((line = in.readLine()) != null) {
15010                        if (line.contains("ignored: updated version")) continue;
15011                        pw.println(line);
15012                    }
15013                } catch (IOException ignored) {
15014                } finally {
15015                    IoUtils.closeQuietly(in);
15016                }
15017            }
15018
15019            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15020                BufferedReader in = null;
15021                String line = null;
15022                try {
15023                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15024                    while ((line = in.readLine()) != null) {
15025                        if (line.contains("ignored: updated version")) continue;
15026                        pw.print("msg,");
15027                        pw.println(line);
15028                    }
15029                } catch (IOException ignored) {
15030                } finally {
15031                    IoUtils.closeQuietly(in);
15032                }
15033            }
15034        }
15035    }
15036
15037    private String dumpDomainString(String packageName) {
15038        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15039        List<IntentFilter> filters = getAllIntentFilters(packageName);
15040
15041        ArraySet<String> result = new ArraySet<>();
15042        if (iviList.size() > 0) {
15043            for (IntentFilterVerificationInfo ivi : iviList) {
15044                for (String host : ivi.getDomains()) {
15045                    result.add(host);
15046                }
15047            }
15048        }
15049        if (filters != null && filters.size() > 0) {
15050            for (IntentFilter filter : filters) {
15051                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15052                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15053                    result.addAll(filter.getHostsList());
15054                }
15055            }
15056        }
15057
15058        StringBuilder sb = new StringBuilder(result.size() * 16);
15059        for (String domain : result) {
15060            if (sb.length() > 0) sb.append(" ");
15061            sb.append(domain);
15062        }
15063        return sb.toString();
15064    }
15065
15066    // ------- apps on sdcard specific code -------
15067    static final boolean DEBUG_SD_INSTALL = false;
15068
15069    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15070
15071    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15072
15073    private boolean mMediaMounted = false;
15074
15075    static String getEncryptKey() {
15076        try {
15077            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15078                    SD_ENCRYPTION_KEYSTORE_NAME);
15079            if (sdEncKey == null) {
15080                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15081                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15082                if (sdEncKey == null) {
15083                    Slog.e(TAG, "Failed to create encryption keys");
15084                    return null;
15085                }
15086            }
15087            return sdEncKey;
15088        } catch (NoSuchAlgorithmException nsae) {
15089            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15090            return null;
15091        } catch (IOException ioe) {
15092            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15093            return null;
15094        }
15095    }
15096
15097    /*
15098     * Update media status on PackageManager.
15099     */
15100    @Override
15101    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15102        int callingUid = Binder.getCallingUid();
15103        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15104            throw new SecurityException("Media status can only be updated by the system");
15105        }
15106        // reader; this apparently protects mMediaMounted, but should probably
15107        // be a different lock in that case.
15108        synchronized (mPackages) {
15109            Log.i(TAG, "Updating external media status from "
15110                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15111                    + (mediaStatus ? "mounted" : "unmounted"));
15112            if (DEBUG_SD_INSTALL)
15113                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15114                        + ", mMediaMounted=" + mMediaMounted);
15115            if (mediaStatus == mMediaMounted) {
15116                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15117                        : 0, -1);
15118                mHandler.sendMessage(msg);
15119                return;
15120            }
15121            mMediaMounted = mediaStatus;
15122        }
15123        // Queue up an async operation since the package installation may take a
15124        // little while.
15125        mHandler.post(new Runnable() {
15126            public void run() {
15127                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15128            }
15129        });
15130    }
15131
15132    /**
15133     * Called by MountService when the initial ASECs to scan are available.
15134     * Should block until all the ASEC containers are finished being scanned.
15135     */
15136    public void scanAvailableAsecs() {
15137        updateExternalMediaStatusInner(true, false, false);
15138        if (mShouldRestoreconData) {
15139            SELinuxMMAC.setRestoreconDone();
15140            mShouldRestoreconData = false;
15141        }
15142    }
15143
15144    /*
15145     * Collect information of applications on external media, map them against
15146     * existing containers and update information based on current mount status.
15147     * Please note that we always have to report status if reportStatus has been
15148     * set to true especially when unloading packages.
15149     */
15150    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15151            boolean externalStorage) {
15152        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15153        int[] uidArr = EmptyArray.INT;
15154
15155        final String[] list = PackageHelper.getSecureContainerList();
15156        if (ArrayUtils.isEmpty(list)) {
15157            Log.i(TAG, "No secure containers found");
15158        } else {
15159            // Process list of secure containers and categorize them
15160            // as active or stale based on their package internal state.
15161
15162            // reader
15163            synchronized (mPackages) {
15164                for (String cid : list) {
15165                    // Leave stages untouched for now; installer service owns them
15166                    if (PackageInstallerService.isStageName(cid)) continue;
15167
15168                    if (DEBUG_SD_INSTALL)
15169                        Log.i(TAG, "Processing container " + cid);
15170                    String pkgName = getAsecPackageName(cid);
15171                    if (pkgName == null) {
15172                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15173                        continue;
15174                    }
15175                    if (DEBUG_SD_INSTALL)
15176                        Log.i(TAG, "Looking for pkg : " + pkgName);
15177
15178                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15179                    if (ps == null) {
15180                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15181                        continue;
15182                    }
15183
15184                    /*
15185                     * Skip packages that are not external if we're unmounting
15186                     * external storage.
15187                     */
15188                    if (externalStorage && !isMounted && !isExternal(ps)) {
15189                        continue;
15190                    }
15191
15192                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15193                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15194                    // The package status is changed only if the code path
15195                    // matches between settings and the container id.
15196                    if (ps.codePathString != null
15197                            && ps.codePathString.startsWith(args.getCodePath())) {
15198                        if (DEBUG_SD_INSTALL) {
15199                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15200                                    + " at code path: " + ps.codePathString);
15201                        }
15202
15203                        // We do have a valid package installed on sdcard
15204                        processCids.put(args, ps.codePathString);
15205                        final int uid = ps.appId;
15206                        if (uid != -1) {
15207                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15208                        }
15209                    } else {
15210                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15211                                + ps.codePathString);
15212                    }
15213                }
15214            }
15215
15216            Arrays.sort(uidArr);
15217        }
15218
15219        // Process packages with valid entries.
15220        if (isMounted) {
15221            if (DEBUG_SD_INSTALL)
15222                Log.i(TAG, "Loading packages");
15223            loadMediaPackages(processCids, uidArr);
15224            startCleaningPackages();
15225            mInstallerService.onSecureContainersAvailable();
15226        } else {
15227            if (DEBUG_SD_INSTALL)
15228                Log.i(TAG, "Unloading packages");
15229            unloadMediaPackages(processCids, uidArr, reportStatus);
15230        }
15231    }
15232
15233    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15234            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15235        final int size = infos.size();
15236        final String[] packageNames = new String[size];
15237        final int[] packageUids = new int[size];
15238        for (int i = 0; i < size; i++) {
15239            final ApplicationInfo info = infos.get(i);
15240            packageNames[i] = info.packageName;
15241            packageUids[i] = info.uid;
15242        }
15243        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15244                finishedReceiver);
15245    }
15246
15247    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15248            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15249        sendResourcesChangedBroadcast(mediaStatus, replacing,
15250                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15251    }
15252
15253    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15254            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15255        int size = pkgList.length;
15256        if (size > 0) {
15257            // Send broadcasts here
15258            Bundle extras = new Bundle();
15259            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15260            if (uidArr != null) {
15261                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15262            }
15263            if (replacing) {
15264                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15265            }
15266            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15267                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15268            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15269        }
15270    }
15271
15272   /*
15273     * Look at potentially valid container ids from processCids If package
15274     * information doesn't match the one on record or package scanning fails,
15275     * the cid is added to list of removeCids. We currently don't delete stale
15276     * containers.
15277     */
15278    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15279        ArrayList<String> pkgList = new ArrayList<String>();
15280        Set<AsecInstallArgs> keys = processCids.keySet();
15281
15282        for (AsecInstallArgs args : keys) {
15283            String codePath = processCids.get(args);
15284            if (DEBUG_SD_INSTALL)
15285                Log.i(TAG, "Loading container : " + args.cid);
15286            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15287            try {
15288                // Make sure there are no container errors first.
15289                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15290                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15291                            + " when installing from sdcard");
15292                    continue;
15293                }
15294                // Check code path here.
15295                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15296                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15297                            + " does not match one in settings " + codePath);
15298                    continue;
15299                }
15300                // Parse package
15301                int parseFlags = mDefParseFlags;
15302                if (args.isExternalAsec()) {
15303                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15304                }
15305                if (args.isFwdLocked()) {
15306                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15307                }
15308
15309                synchronized (mInstallLock) {
15310                    PackageParser.Package pkg = null;
15311                    try {
15312                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15313                    } catch (PackageManagerException e) {
15314                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15315                    }
15316                    // Scan the package
15317                    if (pkg != null) {
15318                        /*
15319                         * TODO why is the lock being held? doPostInstall is
15320                         * called in other places without the lock. This needs
15321                         * to be straightened out.
15322                         */
15323                        // writer
15324                        synchronized (mPackages) {
15325                            retCode = PackageManager.INSTALL_SUCCEEDED;
15326                            pkgList.add(pkg.packageName);
15327                            // Post process args
15328                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15329                                    pkg.applicationInfo.uid);
15330                        }
15331                    } else {
15332                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15333                    }
15334                }
15335
15336            } finally {
15337                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15338                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15339                }
15340            }
15341        }
15342        // writer
15343        synchronized (mPackages) {
15344            // If the platform SDK has changed since the last time we booted,
15345            // we need to re-grant app permission to catch any new ones that
15346            // appear. This is really a hack, and means that apps can in some
15347            // cases get permissions that the user didn't initially explicitly
15348            // allow... it would be nice to have some better way to handle
15349            // this situation.
15350            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15351            if (regrantPermissions)
15352                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15353                        + mSdkVersion + "; regranting permissions for external storage");
15354            mSettings.mExternalSdkPlatform = mSdkVersion;
15355
15356            // Make sure group IDs have been assigned, and any permission
15357            // changes in other apps are accounted for
15358            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15359                    | (regrantPermissions
15360                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15361                            : 0));
15362
15363            mSettings.updateExternalDatabaseVersion();
15364
15365            // can downgrade to reader
15366            // Persist settings
15367            mSettings.writeLPr();
15368        }
15369        // Send a broadcast to let everyone know we are done processing
15370        if (pkgList.size() > 0) {
15371            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15372        }
15373    }
15374
15375   /*
15376     * Utility method to unload a list of specified containers
15377     */
15378    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15379        // Just unmount all valid containers.
15380        for (AsecInstallArgs arg : cidArgs) {
15381            synchronized (mInstallLock) {
15382                arg.doPostDeleteLI(false);
15383           }
15384       }
15385   }
15386
15387    /*
15388     * Unload packages mounted on external media. This involves deleting package
15389     * data from internal structures, sending broadcasts about diabled packages,
15390     * gc'ing to free up references, unmounting all secure containers
15391     * corresponding to packages on external media, and posting a
15392     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15393     * that we always have to post this message if status has been requested no
15394     * matter what.
15395     */
15396    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15397            final boolean reportStatus) {
15398        if (DEBUG_SD_INSTALL)
15399            Log.i(TAG, "unloading media packages");
15400        ArrayList<String> pkgList = new ArrayList<String>();
15401        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15402        final Set<AsecInstallArgs> keys = processCids.keySet();
15403        for (AsecInstallArgs args : keys) {
15404            String pkgName = args.getPackageName();
15405            if (DEBUG_SD_INSTALL)
15406                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15407            // Delete package internally
15408            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15409            synchronized (mInstallLock) {
15410                boolean res = deletePackageLI(pkgName, null, false, null, null,
15411                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15412                if (res) {
15413                    pkgList.add(pkgName);
15414                } else {
15415                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15416                    failedList.add(args);
15417                }
15418            }
15419        }
15420
15421        // reader
15422        synchronized (mPackages) {
15423            // We didn't update the settings after removing each package;
15424            // write them now for all packages.
15425            mSettings.writeLPr();
15426        }
15427
15428        // We have to absolutely send UPDATED_MEDIA_STATUS only
15429        // after confirming that all the receivers processed the ordered
15430        // broadcast when packages get disabled, force a gc to clean things up.
15431        // and unload all the containers.
15432        if (pkgList.size() > 0) {
15433            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15434                    new IIntentReceiver.Stub() {
15435                public void performReceive(Intent intent, int resultCode, String data,
15436                        Bundle extras, boolean ordered, boolean sticky,
15437                        int sendingUser) throws RemoteException {
15438                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15439                            reportStatus ? 1 : 0, 1, keys);
15440                    mHandler.sendMessage(msg);
15441                }
15442            });
15443        } else {
15444            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15445                    keys);
15446            mHandler.sendMessage(msg);
15447        }
15448    }
15449
15450    private void loadPrivatePackages(VolumeInfo vol) {
15451        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15452        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15453        synchronized (mInstallLock) {
15454        synchronized (mPackages) {
15455            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15456            for (PackageSetting ps : packages) {
15457                final PackageParser.Package pkg;
15458                try {
15459                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15460                    loaded.add(pkg.applicationInfo);
15461                } catch (PackageManagerException e) {
15462                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15463                }
15464            }
15465
15466            // TODO: regrant any permissions that changed based since original install
15467
15468            mSettings.writeLPr();
15469        }
15470        }
15471
15472        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15473        sendResourcesChangedBroadcast(true, false, loaded, null);
15474    }
15475
15476    private void unloadPrivatePackages(VolumeInfo vol) {
15477        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15478        synchronized (mInstallLock) {
15479        synchronized (mPackages) {
15480            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15481            for (PackageSetting ps : packages) {
15482                if (ps.pkg == null) continue;
15483
15484                final ApplicationInfo info = ps.pkg.applicationInfo;
15485                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15486                if (deletePackageLI(ps.name, null, false, null, null,
15487                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15488                    unloaded.add(info);
15489                } else {
15490                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15491                }
15492            }
15493
15494            mSettings.writeLPr();
15495        }
15496        }
15497
15498        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15499        sendResourcesChangedBroadcast(false, false, unloaded, null);
15500    }
15501
15502    /**
15503     * Examine all users present on given mounted volume, and destroy data
15504     * belonging to users that are no longer valid, or whose user ID has been
15505     * recycled.
15506     */
15507    private void reconcileUsers(String volumeUuid) {
15508        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15509        if (ArrayUtils.isEmpty(files)) {
15510            Slog.d(TAG, "No users found on " + volumeUuid);
15511            return;
15512        }
15513
15514        for (File file : files) {
15515            if (!file.isDirectory()) continue;
15516
15517            final int userId;
15518            final UserInfo info;
15519            try {
15520                userId = Integer.parseInt(file.getName());
15521                info = sUserManager.getUserInfo(userId);
15522            } catch (NumberFormatException e) {
15523                Slog.w(TAG, "Invalid user directory " + file);
15524                continue;
15525            }
15526
15527            boolean destroyUser = false;
15528            if (info == null) {
15529                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15530                        + " because no matching user was found");
15531                destroyUser = true;
15532            } else {
15533                try {
15534                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15535                } catch (IOException e) {
15536                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15537                            + " because we failed to enforce serial number: " + e);
15538                    destroyUser = true;
15539                }
15540            }
15541
15542            if (destroyUser) {
15543                synchronized (mInstallLock) {
15544                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15545                }
15546            }
15547        }
15548
15549        final UserManager um = mContext.getSystemService(UserManager.class);
15550        for (UserInfo user : um.getUsers()) {
15551            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15552            if (userDir.exists()) continue;
15553
15554            try {
15555                UserManagerService.prepareUserDirectory(userDir);
15556                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15557            } catch (IOException e) {
15558                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15559            }
15560        }
15561    }
15562
15563    /**
15564     * Examine all apps present on given mounted volume, and destroy apps that
15565     * aren't expected, either due to uninstallation or reinstallation on
15566     * another volume.
15567     */
15568    private void reconcileApps(String volumeUuid) {
15569        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15570        if (ArrayUtils.isEmpty(files)) {
15571            Slog.d(TAG, "No apps found on " + volumeUuid);
15572            return;
15573        }
15574
15575        for (File file : files) {
15576            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15577                    && !PackageInstallerService.isStageName(file.getName());
15578            if (!isPackage) {
15579                // Ignore entries which are not packages
15580                continue;
15581            }
15582
15583            boolean destroyApp = false;
15584            String packageName = null;
15585            try {
15586                final PackageLite pkg = PackageParser.parsePackageLite(file,
15587                        PackageParser.PARSE_MUST_BE_APK);
15588                packageName = pkg.packageName;
15589
15590                synchronized (mPackages) {
15591                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15592                    if (ps == null) {
15593                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15594                                + volumeUuid + " because we found no install record");
15595                        destroyApp = true;
15596                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15597                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15598                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15599                        destroyApp = true;
15600                    }
15601                }
15602
15603            } catch (PackageParserException e) {
15604                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15605                destroyApp = true;
15606            }
15607
15608            if (destroyApp) {
15609                synchronized (mInstallLock) {
15610                    if (packageName != null) {
15611                        removeDataDirsLI(volumeUuid, packageName);
15612                    }
15613                    if (file.isDirectory()) {
15614                        mInstaller.rmPackageDir(file.getAbsolutePath());
15615                    } else {
15616                        file.delete();
15617                    }
15618                }
15619            }
15620        }
15621    }
15622
15623    private void unfreezePackage(String packageName) {
15624        synchronized (mPackages) {
15625            final PackageSetting ps = mSettings.mPackages.get(packageName);
15626            if (ps != null) {
15627                ps.frozen = false;
15628            }
15629        }
15630    }
15631
15632    @Override
15633    public int movePackage(final String packageName, final String volumeUuid) {
15634        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15635
15636        final int moveId = mNextMoveId.getAndIncrement();
15637        try {
15638            movePackageInternal(packageName, volumeUuid, moveId);
15639        } catch (PackageManagerException e) {
15640            Slog.w(TAG, "Failed to move " + packageName, e);
15641            mMoveCallbacks.notifyStatusChanged(moveId,
15642                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15643        }
15644        return moveId;
15645    }
15646
15647    private void movePackageInternal(final String packageName, final String volumeUuid,
15648            final int moveId) throws PackageManagerException {
15649        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15650        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15651        final PackageManager pm = mContext.getPackageManager();
15652
15653        final boolean currentAsec;
15654        final String currentVolumeUuid;
15655        final File codeFile;
15656        final String installerPackageName;
15657        final String packageAbiOverride;
15658        final int appId;
15659        final String seinfo;
15660        final String label;
15661
15662        // reader
15663        synchronized (mPackages) {
15664            final PackageParser.Package pkg = mPackages.get(packageName);
15665            final PackageSetting ps = mSettings.mPackages.get(packageName);
15666            if (pkg == null || ps == null) {
15667                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15668            }
15669
15670            if (pkg.applicationInfo.isSystemApp()) {
15671                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15672                        "Cannot move system application");
15673            }
15674
15675            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15676                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15677                        "Package already moved to " + volumeUuid);
15678            }
15679
15680            final File probe = new File(pkg.codePath);
15681            final File probeOat = new File(probe, "oat");
15682            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15683                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15684                        "Move only supported for modern cluster style installs");
15685            }
15686
15687            if (ps.frozen) {
15688                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15689                        "Failed to move already frozen package");
15690            }
15691            ps.frozen = true;
15692
15693            currentAsec = pkg.applicationInfo.isForwardLocked()
15694                    || pkg.applicationInfo.isExternalAsec();
15695            currentVolumeUuid = ps.volumeUuid;
15696            codeFile = new File(pkg.codePath);
15697            installerPackageName = ps.installerPackageName;
15698            packageAbiOverride = ps.cpuAbiOverrideString;
15699            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15700            seinfo = pkg.applicationInfo.seinfo;
15701            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15702        }
15703
15704        // Now that we're guarded by frozen state, kill app during move
15705        killApplication(packageName, appId, "move pkg");
15706
15707        final Bundle extras = new Bundle();
15708        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15709        extras.putString(Intent.EXTRA_TITLE, label);
15710        mMoveCallbacks.notifyCreated(moveId, extras);
15711
15712        int installFlags;
15713        final boolean moveCompleteApp;
15714        final File measurePath;
15715
15716        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15717            installFlags = INSTALL_INTERNAL;
15718            moveCompleteApp = !currentAsec;
15719            measurePath = Environment.getDataAppDirectory(volumeUuid);
15720        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15721            installFlags = INSTALL_EXTERNAL;
15722            moveCompleteApp = false;
15723            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15724        } else {
15725            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15726            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15727                    || !volume.isMountedWritable()) {
15728                unfreezePackage(packageName);
15729                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15730                        "Move location not mounted private volume");
15731            }
15732
15733            Preconditions.checkState(!currentAsec);
15734
15735            installFlags = INSTALL_INTERNAL;
15736            moveCompleteApp = true;
15737            measurePath = Environment.getDataAppDirectory(volumeUuid);
15738        }
15739
15740        final PackageStats stats = new PackageStats(null, -1);
15741        synchronized (mInstaller) {
15742            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15743                unfreezePackage(packageName);
15744                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15745                        "Failed to measure package size");
15746            }
15747        }
15748
15749        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15750                + stats.dataSize);
15751
15752        final long startFreeBytes = measurePath.getFreeSpace();
15753        final long sizeBytes;
15754        if (moveCompleteApp) {
15755            sizeBytes = stats.codeSize + stats.dataSize;
15756        } else {
15757            sizeBytes = stats.codeSize;
15758        }
15759
15760        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15761            unfreezePackage(packageName);
15762            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15763                    "Not enough free space to move");
15764        }
15765
15766        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15767
15768        final CountDownLatch installedLatch = new CountDownLatch(1);
15769        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15770            @Override
15771            public void onUserActionRequired(Intent intent) throws RemoteException {
15772                throw new IllegalStateException();
15773            }
15774
15775            @Override
15776            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15777                    Bundle extras) throws RemoteException {
15778                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15779                        + PackageManager.installStatusToString(returnCode, msg));
15780
15781                installedLatch.countDown();
15782
15783                // Regardless of success or failure of the move operation,
15784                // always unfreeze the package
15785                unfreezePackage(packageName);
15786
15787                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15788                switch (status) {
15789                    case PackageInstaller.STATUS_SUCCESS:
15790                        mMoveCallbacks.notifyStatusChanged(moveId,
15791                                PackageManager.MOVE_SUCCEEDED);
15792                        break;
15793                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15794                        mMoveCallbacks.notifyStatusChanged(moveId,
15795                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15796                        break;
15797                    default:
15798                        mMoveCallbacks.notifyStatusChanged(moveId,
15799                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15800                        break;
15801                }
15802            }
15803        };
15804
15805        final MoveInfo move;
15806        if (moveCompleteApp) {
15807            // Kick off a thread to report progress estimates
15808            new Thread() {
15809                @Override
15810                public void run() {
15811                    while (true) {
15812                        try {
15813                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15814                                break;
15815                            }
15816                        } catch (InterruptedException ignored) {
15817                        }
15818
15819                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15820                        final int progress = 10 + (int) MathUtils.constrain(
15821                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15822                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15823                    }
15824                }
15825            }.start();
15826
15827            final String dataAppName = codeFile.getName();
15828            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15829                    dataAppName, appId, seinfo);
15830        } else {
15831            move = null;
15832        }
15833
15834        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15835
15836        final Message msg = mHandler.obtainMessage(INIT_COPY);
15837        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15838        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15839                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15840        mHandler.sendMessage(msg);
15841    }
15842
15843    @Override
15844    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15846
15847        final int realMoveId = mNextMoveId.getAndIncrement();
15848        final Bundle extras = new Bundle();
15849        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15850        mMoveCallbacks.notifyCreated(realMoveId, extras);
15851
15852        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15853            @Override
15854            public void onCreated(int moveId, Bundle extras) {
15855                // Ignored
15856            }
15857
15858            @Override
15859            public void onStatusChanged(int moveId, int status, long estMillis) {
15860                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15861            }
15862        };
15863
15864        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15865        storage.setPrimaryStorageUuid(volumeUuid, callback);
15866        return realMoveId;
15867    }
15868
15869    @Override
15870    public int getMoveStatus(int moveId) {
15871        mContext.enforceCallingOrSelfPermission(
15872                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15873        return mMoveCallbacks.mLastStatus.get(moveId);
15874    }
15875
15876    @Override
15877    public void registerMoveCallback(IPackageMoveObserver callback) {
15878        mContext.enforceCallingOrSelfPermission(
15879                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15880        mMoveCallbacks.register(callback);
15881    }
15882
15883    @Override
15884    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15885        mContext.enforceCallingOrSelfPermission(
15886                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15887        mMoveCallbacks.unregister(callback);
15888    }
15889
15890    @Override
15891    public boolean setInstallLocation(int loc) {
15892        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15893                null);
15894        if (getInstallLocation() == loc) {
15895            return true;
15896        }
15897        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15898                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15899            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15900                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15901            return true;
15902        }
15903        return false;
15904   }
15905
15906    @Override
15907    public int getInstallLocation() {
15908        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15909                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15910                PackageHelper.APP_INSTALL_AUTO);
15911    }
15912
15913    /** Called by UserManagerService */
15914    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15915        mDirtyUsers.remove(userHandle);
15916        mSettings.removeUserLPw(userHandle);
15917        mPendingBroadcasts.remove(userHandle);
15918        if (mInstaller != null) {
15919            // Technically, we shouldn't be doing this with the package lock
15920            // held.  However, this is very rare, and there is already so much
15921            // other disk I/O going on, that we'll let it slide for now.
15922            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15923            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15924                final String volumeUuid = vol.getFsUuid();
15925                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15926                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15927            }
15928        }
15929        mUserNeedsBadging.delete(userHandle);
15930        removeUnusedPackagesLILPw(userManager, userHandle);
15931    }
15932
15933    /**
15934     * We're removing userHandle and would like to remove any downloaded packages
15935     * that are no longer in use by any other user.
15936     * @param userHandle the user being removed
15937     */
15938    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15939        final boolean DEBUG_CLEAN_APKS = false;
15940        int [] users = userManager.getUserIdsLPr();
15941        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15942        while (psit.hasNext()) {
15943            PackageSetting ps = psit.next();
15944            if (ps.pkg == null) {
15945                continue;
15946            }
15947            final String packageName = ps.pkg.packageName;
15948            // Skip over if system app
15949            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15950                continue;
15951            }
15952            if (DEBUG_CLEAN_APKS) {
15953                Slog.i(TAG, "Checking package " + packageName);
15954            }
15955            boolean keep = false;
15956            for (int i = 0; i < users.length; i++) {
15957                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15958                    keep = true;
15959                    if (DEBUG_CLEAN_APKS) {
15960                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15961                                + users[i]);
15962                    }
15963                    break;
15964                }
15965            }
15966            if (!keep) {
15967                if (DEBUG_CLEAN_APKS) {
15968                    Slog.i(TAG, "  Removing package " + packageName);
15969                }
15970                mHandler.post(new Runnable() {
15971                    public void run() {
15972                        deletePackageX(packageName, userHandle, 0);
15973                    } //end run
15974                });
15975            }
15976        }
15977    }
15978
15979    /** Called by UserManagerService */
15980    void createNewUserLILPw(int userHandle) {
15981        if (mInstaller != null) {
15982            mInstaller.createUserConfig(userHandle);
15983            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15984            applyFactoryDefaultBrowserLPw(userHandle);
15985            primeDomainVerificationsLPw(userHandle);
15986        }
15987    }
15988
15989    void newUserCreated(final int userHandle) {
15990        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15991    }
15992
15993    @Override
15994    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15995        mContext.enforceCallingOrSelfPermission(
15996                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15997                "Only package verification agents can read the verifier device identity");
15998
15999        synchronized (mPackages) {
16000            return mSettings.getVerifierDeviceIdentityLPw();
16001        }
16002    }
16003
16004    @Override
16005    public void setPermissionEnforced(String permission, boolean enforced) {
16006        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16007        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16008            synchronized (mPackages) {
16009                if (mSettings.mReadExternalStorageEnforced == null
16010                        || mSettings.mReadExternalStorageEnforced != enforced) {
16011                    mSettings.mReadExternalStorageEnforced = enforced;
16012                    mSettings.writeLPr();
16013                }
16014            }
16015            // kill any non-foreground processes so we restart them and
16016            // grant/revoke the GID.
16017            final IActivityManager am = ActivityManagerNative.getDefault();
16018            if (am != null) {
16019                final long token = Binder.clearCallingIdentity();
16020                try {
16021                    am.killProcessesBelowForeground("setPermissionEnforcement");
16022                } catch (RemoteException e) {
16023                } finally {
16024                    Binder.restoreCallingIdentity(token);
16025                }
16026            }
16027        } else {
16028            throw new IllegalArgumentException("No selective enforcement for " + permission);
16029        }
16030    }
16031
16032    @Override
16033    @Deprecated
16034    public boolean isPermissionEnforced(String permission) {
16035        return true;
16036    }
16037
16038    @Override
16039    public boolean isStorageLow() {
16040        final long token = Binder.clearCallingIdentity();
16041        try {
16042            final DeviceStorageMonitorInternal
16043                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16044            if (dsm != null) {
16045                return dsm.isMemoryLow();
16046            } else {
16047                return false;
16048            }
16049        } finally {
16050            Binder.restoreCallingIdentity(token);
16051        }
16052    }
16053
16054    @Override
16055    public IPackageInstaller getPackageInstaller() {
16056        return mInstallerService;
16057    }
16058
16059    private boolean userNeedsBadging(int userId) {
16060        int index = mUserNeedsBadging.indexOfKey(userId);
16061        if (index < 0) {
16062            final UserInfo userInfo;
16063            final long token = Binder.clearCallingIdentity();
16064            try {
16065                userInfo = sUserManager.getUserInfo(userId);
16066            } finally {
16067                Binder.restoreCallingIdentity(token);
16068            }
16069            final boolean b;
16070            if (userInfo != null && userInfo.isManagedProfile()) {
16071                b = true;
16072            } else {
16073                b = false;
16074            }
16075            mUserNeedsBadging.put(userId, b);
16076            return b;
16077        }
16078        return mUserNeedsBadging.valueAt(index);
16079    }
16080
16081    @Override
16082    public KeySet getKeySetByAlias(String packageName, String alias) {
16083        if (packageName == null || alias == null) {
16084            return null;
16085        }
16086        synchronized(mPackages) {
16087            final PackageParser.Package pkg = mPackages.get(packageName);
16088            if (pkg == null) {
16089                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16090                throw new IllegalArgumentException("Unknown package: " + packageName);
16091            }
16092            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16093            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16094        }
16095    }
16096
16097    @Override
16098    public KeySet getSigningKeySet(String packageName) {
16099        if (packageName == null) {
16100            return null;
16101        }
16102        synchronized(mPackages) {
16103            final PackageParser.Package pkg = mPackages.get(packageName);
16104            if (pkg == null) {
16105                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16106                throw new IllegalArgumentException("Unknown package: " + packageName);
16107            }
16108            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16109                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16110                throw new SecurityException("May not access signing KeySet of other apps.");
16111            }
16112            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16113            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16114        }
16115    }
16116
16117    @Override
16118    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16119        if (packageName == null || ks == null) {
16120            return false;
16121        }
16122        synchronized(mPackages) {
16123            final PackageParser.Package pkg = mPackages.get(packageName);
16124            if (pkg == null) {
16125                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16126                throw new IllegalArgumentException("Unknown package: " + packageName);
16127            }
16128            IBinder ksh = ks.getToken();
16129            if (ksh instanceof KeySetHandle) {
16130                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16131                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16132            }
16133            return false;
16134        }
16135    }
16136
16137    @Override
16138    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16139        if (packageName == null || ks == null) {
16140            return false;
16141        }
16142        synchronized(mPackages) {
16143            final PackageParser.Package pkg = mPackages.get(packageName);
16144            if (pkg == null) {
16145                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16146                throw new IllegalArgumentException("Unknown package: " + packageName);
16147            }
16148            IBinder ksh = ks.getToken();
16149            if (ksh instanceof KeySetHandle) {
16150                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16151                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16152            }
16153            return false;
16154        }
16155    }
16156
16157    public void getUsageStatsIfNoPackageUsageInfo() {
16158        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16159            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16160            if (usm == null) {
16161                throw new IllegalStateException("UsageStatsManager must be initialized");
16162            }
16163            long now = System.currentTimeMillis();
16164            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16165            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16166                String packageName = entry.getKey();
16167                PackageParser.Package pkg = mPackages.get(packageName);
16168                if (pkg == null) {
16169                    continue;
16170                }
16171                UsageStats usage = entry.getValue();
16172                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16173                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16174            }
16175        }
16176    }
16177
16178    /**
16179     * Check and throw if the given before/after packages would be considered a
16180     * downgrade.
16181     */
16182    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16183            throws PackageManagerException {
16184        if (after.versionCode < before.mVersionCode) {
16185            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16186                    "Update version code " + after.versionCode + " is older than current "
16187                    + before.mVersionCode);
16188        } else if (after.versionCode == before.mVersionCode) {
16189            if (after.baseRevisionCode < before.baseRevisionCode) {
16190                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16191                        "Update base revision code " + after.baseRevisionCode
16192                        + " is older than current " + before.baseRevisionCode);
16193            }
16194
16195            if (!ArrayUtils.isEmpty(after.splitNames)) {
16196                for (int i = 0; i < after.splitNames.length; i++) {
16197                    final String splitName = after.splitNames[i];
16198                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16199                    if (j != -1) {
16200                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16201                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16202                                    "Update split " + splitName + " revision code "
16203                                    + after.splitRevisionCodes[i] + " is older than current "
16204                                    + before.splitRevisionCodes[j]);
16205                        }
16206                    }
16207                }
16208            }
16209        }
16210    }
16211
16212    private static class MoveCallbacks extends Handler {
16213        private static final int MSG_CREATED = 1;
16214        private static final int MSG_STATUS_CHANGED = 2;
16215
16216        private final RemoteCallbackList<IPackageMoveObserver>
16217                mCallbacks = new RemoteCallbackList<>();
16218
16219        private final SparseIntArray mLastStatus = new SparseIntArray();
16220
16221        public MoveCallbacks(Looper looper) {
16222            super(looper);
16223        }
16224
16225        public void register(IPackageMoveObserver callback) {
16226            mCallbacks.register(callback);
16227        }
16228
16229        public void unregister(IPackageMoveObserver callback) {
16230            mCallbacks.unregister(callback);
16231        }
16232
16233        @Override
16234        public void handleMessage(Message msg) {
16235            final SomeArgs args = (SomeArgs) msg.obj;
16236            final int n = mCallbacks.beginBroadcast();
16237            for (int i = 0; i < n; i++) {
16238                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16239                try {
16240                    invokeCallback(callback, msg.what, args);
16241                } catch (RemoteException ignored) {
16242                }
16243            }
16244            mCallbacks.finishBroadcast();
16245            args.recycle();
16246        }
16247
16248        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16249                throws RemoteException {
16250            switch (what) {
16251                case MSG_CREATED: {
16252                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16253                    break;
16254                }
16255                case MSG_STATUS_CHANGED: {
16256                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16257                    break;
16258                }
16259            }
16260        }
16261
16262        private void notifyCreated(int moveId, Bundle extras) {
16263            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16264
16265            final SomeArgs args = SomeArgs.obtain();
16266            args.argi1 = moveId;
16267            args.arg2 = extras;
16268            obtainMessage(MSG_CREATED, args).sendToTarget();
16269        }
16270
16271        private void notifyStatusChanged(int moveId, int status) {
16272            notifyStatusChanged(moveId, status, -1);
16273        }
16274
16275        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16276            Slog.v(TAG, "Move " + moveId + " status " + status);
16277
16278            final SomeArgs args = SomeArgs.obtain();
16279            args.argi1 = moveId;
16280            args.argi2 = status;
16281            args.arg3 = estMillis;
16282            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16283
16284            synchronized (mLastStatus) {
16285                mLastStatus.put(moveId, status);
16286            }
16287        }
16288    }
16289
16290    private final class OnPermissionChangeListeners extends Handler {
16291        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16292
16293        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16294                new RemoteCallbackList<>();
16295
16296        public OnPermissionChangeListeners(Looper looper) {
16297            super(looper);
16298        }
16299
16300        @Override
16301        public void handleMessage(Message msg) {
16302            switch (msg.what) {
16303                case MSG_ON_PERMISSIONS_CHANGED: {
16304                    final int uid = msg.arg1;
16305                    handleOnPermissionsChanged(uid);
16306                } break;
16307            }
16308        }
16309
16310        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16311            mPermissionListeners.register(listener);
16312
16313        }
16314
16315        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16316            mPermissionListeners.unregister(listener);
16317        }
16318
16319        public void onPermissionsChanged(int uid) {
16320            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16321                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16322            }
16323        }
16324
16325        private void handleOnPermissionsChanged(int uid) {
16326            final int count = mPermissionListeners.beginBroadcast();
16327            try {
16328                for (int i = 0; i < count; i++) {
16329                    IOnPermissionsChangeListener callback = mPermissionListeners
16330                            .getBroadcastItem(i);
16331                    try {
16332                        callback.onPermissionsChanged(uid);
16333                    } catch (RemoteException e) {
16334                        Log.e(TAG, "Permission listener is dead", e);
16335                    }
16336                }
16337            } finally {
16338                mPermissionListeners.finishBroadcast();
16339            }
16340        }
16341    }
16342
16343    private class PackageManagerInternalImpl extends PackageManagerInternal {
16344        @Override
16345        public void setLocationPackagesProvider(PackagesProvider provider) {
16346            synchronized (mPackages) {
16347                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16348            }
16349        }
16350
16351        @Override
16352        public void setImePackagesProvider(PackagesProvider provider) {
16353            synchronized (mPackages) {
16354                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16355            }
16356        }
16357
16358        @Override
16359        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16360            synchronized (mPackages) {
16361                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16362            }
16363        }
16364
16365        @Override
16366        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16367            synchronized (mPackages) {
16368                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16369            }
16370        }
16371
16372        @Override
16373        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16374            synchronized (mPackages) {
16375                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16376            }
16377        }
16378
16379        @Override
16380        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16381            synchronized (mPackages) {
16382                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16383            }
16384        }
16385
16386        @Override
16387        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16388            synchronized (mPackages) {
16389                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16390                        packageName, userId);
16391            }
16392        }
16393
16394        @Override
16395        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16396            synchronized (mPackages) {
16397                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16398                        packageName, userId);
16399            }
16400        }
16401    }
16402
16403    @Override
16404    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16405        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16406        synchronized (mPackages) {
16407            final long identity = Binder.clearCallingIdentity();
16408            try {
16409                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16410                        packageNames, userId);
16411            } finally {
16412                Binder.restoreCallingIdentity(identity);
16413            }
16414        }
16415    }
16416
16417    private static void enforceSystemOrPhoneCaller(String tag) {
16418        int callingUid = Binder.getCallingUid();
16419        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16420            throw new SecurityException(
16421                    "Cannot call " + tag + " from UID " + callingUid);
16422        }
16423    }
16424}
16425